8997f68409231de05c9bd8a8a68c720f2f3bc3ed
[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 0
59 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
60 #else
61 #define DEFAULT_PRI_DEBUG 0
62 #endif
63
64 static int pri_matchdigittimeout = 3000;
65
66 static int pri_gendigittimeout = 8000;
67
68 #define DCHAN_NOTINALARM  (1 << 0)
69 #define DCHAN_UP          (1 << 1)
70
71 /* Defines to help decode the encoded event channel id. */
72 #define PRI_CHANNEL(p)  ((p) & 0xff)
73 #define PRI_SPAN(p)             (((p) >> 8) & 0xff)
74 #define PRI_EXPLICIT    (1 << 16)
75 #define PRI_CIS_CALL    (1 << 17)       /* Call is using the D channel only. */
76 #define PRI_HELD_CALL   (1 << 18)
77
78
79 #define DCHAN_AVAILABLE (DCHAN_NOTINALARM | DCHAN_UP)
80
81 #define PRI_DEADLOCK_AVOIDANCE(p) \
82         do { \
83                 sig_pri_unlock_private(p); \
84                 usleep(1); \
85                 sig_pri_lock_private(p); \
86         } while (0)
87
88 static int pri_active_dchan_index(struct sig_pri_pri *pri);
89
90 static inline void pri_rel(struct sig_pri_pri *pri)
91 {
92         ast_mutex_unlock(&pri->lock);
93 }
94
95 static unsigned int PVT_TO_CHANNEL(struct sig_pri_chan *p)
96 {
97         int res = (((p)->prioffset) | ((p)->logicalspan << 8) | (p->mastertrunkgroup ? PRI_EXPLICIT : 0));
98         ast_debug(5, "prioffset: %d mastertrunkgroup: %d logicalspan: %d result: %d\n",
99                 p->prioffset, p->mastertrunkgroup, p->logicalspan, res);
100
101         return res;
102 }
103
104 static void sig_pri_handle_dchan_exception(struct sig_pri_pri *pri, int index)
105 {
106         if (pri->calls->handle_dchan_exception)
107                 pri->calls->handle_dchan_exception(pri, index);
108 }
109
110 static void sig_pri_set_dialing(struct sig_pri_chan *p, int flag)
111 {
112         if (p->calls->set_dialing)
113                 p->calls->set_dialing(p->chan_pvt, flag);
114 }
115
116 static void sig_pri_set_digital(struct sig_pri_chan *p, int flag)
117 {
118         p->digital = flag;
119         if (p->calls->set_digital)
120                 p->calls->set_digital(p->chan_pvt, flag);
121 }
122
123 /*!
124  * \internal
125  * \brief Set the caller id information in the parent module.
126  * \since 1.8
127  *
128  * \param p sig_pri channel structure.
129  *
130  * \return Nothing
131  */
132 static void sig_pri_set_caller_id(struct sig_pri_chan *p)
133 {
134         struct ast_party_caller caller;
135
136         if (p->calls->set_callerid) {
137                 ast_party_caller_init(&caller);
138                 caller.id.number = p->cid_num;
139                 caller.id.name = p->cid_name;
140                 if (!ast_strlen_zero(p->cid_subaddr)) {
141                         caller.id.subaddress.valid = 1;
142                         //caller.id.subaddress.type = 0;/* nsap */
143                         //caller.id.subaddress.odd_even_indicator = 0;
144                         caller.id.subaddress.str = p->cid_subaddr;
145                 }
146                 caller.id.number_type = p->cid_ton;
147                 caller.id.number_presentation = p->callingpres;
148                 caller.ani = p->cid_ani;
149                 caller.ani2 = p->cid_ani2;
150                 p->calls->set_callerid(p->chan_pvt, &caller);
151         }
152 }
153
154 /*!
155  * \internal
156  * \brief Set the Dialed Number Identifier.
157  * \since 1.8
158  *
159  * \param p sig_pri channel structure.
160  * \param dnid Dialed Number Identifier string.
161  *
162  * \return Nothing
163  */
164 static void sig_pri_set_dnid(struct sig_pri_chan *p, const char *dnid)
165 {
166         if (p->calls->set_dnid) {
167                 p->calls->set_dnid(p->chan_pvt, dnid);
168         }
169 }
170
171 /*!
172  * \internal
173  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
174  * \since 1.8
175  *
176  * \param p sig_pri channel structure.
177  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
178  *
179  * \return Nothing
180  */
181 static void sig_pri_set_rdnis(struct sig_pri_chan *p, const char *rdnis)
182 {
183         if (p->calls->set_rdnis) {
184                 p->calls->set_rdnis(p->chan_pvt, rdnis);
185         }
186 }
187
188 static void sig_pri_unlock_private(struct sig_pri_chan *p)
189 {
190         if (p->calls->unlock_private)
191                 p->calls->unlock_private(p->chan_pvt);
192 }
193
194 static void sig_pri_lock_private(struct sig_pri_chan *p)
195 {
196         if (p->calls->lock_private)
197                 p->calls->lock_private(p->chan_pvt);
198 }
199
200 static inline int pri_grab(struct sig_pri_chan *p, struct sig_pri_pri *pri)
201 {
202         int res;
203         /* Grab the lock first */
204         do {
205                 res = ast_mutex_trylock(&pri->lock);
206                 if (res) {
207                         PRI_DEADLOCK_AVOIDANCE(p);
208                 }
209         } while (res);
210         /* Then break the poll */
211         pthread_kill(pri->master, SIGURG);
212         return 0;
213 }
214
215 /*!
216  * \internal
217  * \brief Convert PRI redirecting reason to asterisk version.
218  * \since 1.8
219  *
220  * \param pri_reason PRI redirecting reason.
221  *
222  * \return Equivalent asterisk redirecting reason value.
223  */
224 static enum AST_REDIRECTING_REASON pri_to_ast_reason(int pri_reason)
225 {
226         enum AST_REDIRECTING_REASON ast_reason;
227
228         switch (pri_reason) {
229         case PRI_REDIR_FORWARD_ON_BUSY:
230                 ast_reason = AST_REDIRECTING_REASON_USER_BUSY;
231                 break;
232         case PRI_REDIR_FORWARD_ON_NO_REPLY:
233                 ast_reason = AST_REDIRECTING_REASON_NO_ANSWER;
234                 break;
235         case PRI_REDIR_DEFLECTION:
236                 ast_reason = AST_REDIRECTING_REASON_DEFLECTION;
237                 break;
238         case PRI_REDIR_UNCONDITIONAL:
239                 ast_reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
240                 break;
241         case PRI_REDIR_UNKNOWN:
242         default:
243                 ast_reason = AST_REDIRECTING_REASON_UNKNOWN;
244                 break;
245         }
246
247         return ast_reason;
248 }
249
250 /*!
251  * \internal
252  * \brief Convert asterisk redirecting reason to PRI version.
253  * \since 1.8
254  *
255  * \param ast_reason Asterisk redirecting reason.
256  *
257  * \return Equivalent PRI redirecting reason value.
258  */
259 static int ast_to_pri_reason(enum AST_REDIRECTING_REASON ast_reason)
260 {
261         int pri_reason;
262
263         switch (ast_reason) {
264         case AST_REDIRECTING_REASON_USER_BUSY:
265                 pri_reason = PRI_REDIR_FORWARD_ON_BUSY;
266                 break;
267         case AST_REDIRECTING_REASON_NO_ANSWER:
268                 pri_reason = PRI_REDIR_FORWARD_ON_NO_REPLY;
269                 break;
270         case AST_REDIRECTING_REASON_UNCONDITIONAL:
271                 pri_reason = PRI_REDIR_UNCONDITIONAL;
272                 break;
273         case AST_REDIRECTING_REASON_DEFLECTION:
274                 pri_reason = PRI_REDIR_DEFLECTION;
275                 break;
276         case AST_REDIRECTING_REASON_UNKNOWN:
277         default:
278                 pri_reason = PRI_REDIR_UNKNOWN;
279                 break;
280         }
281
282         return pri_reason;
283 }
284
285 /*!
286  * \internal
287  * \brief Convert PRI number presentation to asterisk version.
288  * \since 1.8
289  *
290  * \param pri_presentation PRI number presentation.
291  *
292  * \return Equivalent asterisk number presentation value.
293  */
294 static int pri_to_ast_presentation(int pri_presentation)
295 {
296         int ast_presentation;
297
298         switch (pri_presentation) {
299         case PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
300                 ast_presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
301                 break;
302         case PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
303                 ast_presentation = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
304                 break;
305         case PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
306                 ast_presentation = AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN;
307                 break;
308         case PRES_ALLOWED_NETWORK_NUMBER:
309                 ast_presentation = AST_PRES_ALLOWED_NETWORK_NUMBER;
310                 break;
311         case PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
312                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
313                 break;
314         case PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
315                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
316                 break;
317         case PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
318                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN;
319                 break;
320         case PRES_PROHIB_NETWORK_NUMBER:
321                 ast_presentation = AST_PRES_PROHIB_NETWORK_NUMBER;
322                 break;
323         case PRES_NUMBER_NOT_AVAILABLE:
324                 ast_presentation = AST_PRES_NUMBER_NOT_AVAILABLE;
325                 break;
326         default:
327                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
328                 break;
329         }
330
331         return ast_presentation;
332 }
333
334 /*!
335  * \internal
336  * \brief Convert asterisk number presentation to PRI version.
337  * \since 1.8
338  *
339  * \param ast_presentation Asterisk number presentation.
340  *
341  * \return Equivalent PRI number presentation value.
342  */
343 static int ast_to_pri_presentation(int ast_presentation)
344 {
345         int pri_presentation;
346
347         switch (ast_presentation) {
348         case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
349                 pri_presentation = PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
350                 break;
351         case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
352                 pri_presentation = PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
353                 break;
354         case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
355                 pri_presentation = PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN;
356                 break;
357         case AST_PRES_ALLOWED_NETWORK_NUMBER:
358                 pri_presentation = PRES_ALLOWED_NETWORK_NUMBER;
359                 break;
360         case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
361                 pri_presentation = PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
362                 break;
363         case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
364                 pri_presentation = PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
365                 break;
366         case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
367                 pri_presentation = PRES_PROHIB_USER_NUMBER_FAILED_SCREEN;
368                 break;
369         case AST_PRES_PROHIB_NETWORK_NUMBER:
370                 pri_presentation = PRES_PROHIB_NETWORK_NUMBER;
371                 break;
372         case AST_PRES_NUMBER_NOT_AVAILABLE:
373                 pri_presentation = PRES_NUMBER_NOT_AVAILABLE;
374                 break;
375         default:
376                 pri_presentation = PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
377                 break;
378         }
379
380         return pri_presentation;
381 }
382
383 /*!
384  * \internal
385  * \brief Determine the overall presentation value for the given party.
386  * \since 1.8
387  *
388  * \param id Party to determine the overall presentation value.
389  *
390  * \return Overall presentation value for the given party converted to ast values.
391  */
392 static int overall_ast_presentation(const struct pri_party_id *id)
393 {
394         int number_priority;
395         int number_value;
396         int number_screening;
397         int name_priority;
398         int name_value;
399
400         /* Determine name presentation priority. */
401         if (!id->name.valid) {
402                 name_value = PRI_PRES_UNAVAILABLE;
403                 name_priority = 3;
404         } else {
405                 name_value = id->name.presentation & PRI_PRES_RESTRICTION;
406                 switch (name_value) {
407                 case PRI_PRES_RESTRICTED:
408                         name_priority = 0;
409                         break;
410                 case PRI_PRES_ALLOWED:
411                         name_priority = 1;
412                         break;
413                 case PRI_PRES_UNAVAILABLE:
414                         name_priority = 2;
415                         break;
416                 default:
417                         name_value = PRI_PRES_UNAVAILABLE;
418                         name_priority = 3;
419                         break;
420                 }
421         }
422
423         /* Determine number presentation priority. */
424         if (!id->number.valid) {
425                 number_screening = PRI_PRES_USER_NUMBER_UNSCREENED;
426                 number_value = PRI_PRES_UNAVAILABLE;
427                 number_priority = 3;
428         } else {
429                 number_screening = id->number.presentation & PRI_PRES_NUMBER_TYPE;
430                 number_value = id->number.presentation & PRI_PRES_RESTRICTION;
431                 switch (number_value) {
432                 case PRI_PRES_RESTRICTED:
433                         number_priority = 0;
434                         break;
435                 case PRI_PRES_ALLOWED:
436                         number_priority = 1;
437                         break;
438                 case PRI_PRES_UNAVAILABLE:
439                         number_priority = 2;
440                         break;
441                 default:
442                         number_screening = PRI_PRES_USER_NUMBER_UNSCREENED;
443                         number_value = PRI_PRES_UNAVAILABLE;
444                         number_priority = 3;
445                         break;
446                 }
447         }
448
449         /* Select the wining presentation value. */
450         if (name_priority < number_priority) {
451                 number_value = name_value;
452         }
453
454         return pri_to_ast_presentation(number_value | number_screening);
455 }
456
457 #if defined(HAVE_PRI_SUBADDR)
458 /*!
459  * \internal
460  * \brief Fill in the asterisk party subaddress from the given PRI party subaddress.
461  * \since 1.8
462  *
463  * \param ast_subaddress Asterisk party subaddress structure.
464  * \param pri_subaddress PRI party subaddress structure.
465  *
466  * \return Nothing
467  *
468  */
469 static void sig_pri_set_subaddress(struct ast_party_subaddress *ast_subaddress, const struct pri_party_subaddress *pri_subaddress)
470 {
471         char *cnum, *ptr;
472         int x, len;
473
474         if (ast_subaddress->str) {
475                 ast_free(ast_subaddress->str);
476         }
477         if (pri_subaddress->length <= 0) {
478                 ast_party_subaddress_init(ast_subaddress);
479                 return;
480         }
481
482         if (!pri_subaddress->type) {
483                 /* NSAP */
484                 ast_subaddress->str = ast_strdup((char *) pri_subaddress->data);
485         } else {
486                 /* User Specified */
487                 if (!(cnum = ast_malloc(2 * pri_subaddress->length + 1))) {
488                         ast_party_subaddress_init(ast_subaddress);
489                         return;
490                 }
491
492                 ptr = cnum;
493                 len = pri_subaddress->length - 1; /* -1 account for zero based indexing */
494                 for (x = 0; x < len; ++x) {
495                         ptr += sprintf(ptr, "%02x", pri_subaddress->data[x]);
496                 }
497
498                 if (pri_subaddress->odd_even_indicator) {
499                         /* ODD */
500                         sprintf(ptr, "%01x", (pri_subaddress->data[len]) >> 4);
501                 } else {
502                         /* EVEN */
503                         sprintf(ptr, "%02x", pri_subaddress->data[len]);
504                 }
505                 ast_subaddress->str = cnum;
506         }
507         ast_subaddress->type = pri_subaddress->type;
508         ast_subaddress->odd_even_indicator = pri_subaddress->odd_even_indicator;
509         ast_subaddress->valid = 1;
510 }
511 #endif  /* defined(HAVE_PRI_SUBADDR) */
512
513 #if defined(HAVE_PRI_SUBADDR)
514 static unsigned char ast_pri_pack_hex_char(char c)
515 {
516         unsigned char res;
517
518         if (c < '0') {
519                 res = 0;
520         } else if (c < ('9' + 1)) {
521                 res = c - '0';
522         } else if (c < 'A') {
523                 res = 0;
524         } else if (c < ('F' + 1)) {
525                 res = c - 'A' + 10;
526         } else if (c < 'a') {
527                 res = 0;
528         } else if (c < ('f' + 1)) {
529                 res = c - 'a' + 10;
530         } else {
531                 res = 0;
532         }
533         return res;
534 }
535 #endif  /* defined(HAVE_PRI_SUBADDR) */
536
537 #if defined(HAVE_PRI_SUBADDR)
538 /*!
539  * \internal
540  * \brief Convert a null terminated hexadecimal string to a packed hex byte array.
541  * \details left justified, with 0 padding if odd length.
542  * \since 1.8
543  *
544  * \param dst pointer to packed byte array.
545  * \param src pointer to null terminated hexadecimal string.
546  * \param maxlen destination array size.
547  *
548  * \return Length of byte array
549  *
550  * \note The dst is not an ASCIIz string.
551  * \note The src is an ASCIIz hex string.
552  */
553 static int ast_pri_pack_hex_string(unsigned char *dst, char *src, int maxlen)
554 {
555         int res = 0;
556         int len = strlen(src);
557
558         if (len > (2 * maxlen)) {
559                 len = 2 * maxlen;
560         }
561
562         res = len / 2 + len % 2;
563
564         while (len > 1) {
565                 *dst = ast_pri_pack_hex_char(*src) << 4;
566                 src++;
567                 *dst |= ast_pri_pack_hex_char(*src);
568                 dst++, src++;
569                 len -= 2;
570         }
571         if (len) { /* 1 left */
572                 *dst = ast_pri_pack_hex_char(*src) << 4;
573         }
574         return res;
575 }
576 #endif  /* defined(HAVE_PRI_SUBADDR) */
577
578 #if defined(HAVE_PRI_SUBADDR)
579 /*!
580  * \internal
581  * \brief Fill in the PRI party subaddress from the given asterisk party subaddress.
582  * \since 1.8
583  *
584  * \param pri_subaddress PRI party subaddress structure.
585  * \param ast_subaddress Asterisk party subaddress structure.
586  *
587  * \return Nothing
588  *
589  * \note Assumes that pri_subaddress has been previously memset to zero.
590  */
591 static void sig_pri_party_subaddress_from_ast(struct pri_party_subaddress *pri_subaddress, const struct ast_party_subaddress *ast_subaddress)
592 {
593         if (ast_subaddress->valid && !ast_strlen_zero(ast_subaddress->str)) {
594                 pri_subaddress->type = ast_subaddress->type;
595                 if (!ast_subaddress->type) {
596                         /* 0 = NSAP */
597                         ast_copy_string((char *) pri_subaddress->data, ast_subaddress->str,
598                                 sizeof(pri_subaddress->data));
599                         pri_subaddress->length = strlen((char *) pri_subaddress->data);
600                         pri_subaddress->odd_even_indicator = 0;
601                         pri_subaddress->valid = 1;
602                 } else {
603                         /* 2 = User Specified */
604                         /*
605                          * Copy HexString to packed HexData,
606                          * if odd length then right pad trailing byte with 0
607                          */
608                         int length = ast_pri_pack_hex_string(pri_subaddress->data,
609                                 ast_subaddress->str, sizeof(pri_subaddress->data));
610
611                         pri_subaddress->length = length;
612                         pri_subaddress->odd_even_indicator = (length & 1);
613                         pri_subaddress->valid = 1;
614                 }
615         }
616 }
617 #endif  /* defined(HAVE_PRI_SUBADDR) */
618
619 /*!
620  * \internal
621  * \brief Fill in the PRI party id from the given asterisk party id.
622  * \since 1.8
623  *
624  * \param pri_id PRI party id structure.
625  * \param ast_id Asterisk party id structure.
626  *
627  * \return Nothing
628  *
629  * \note Assumes that pri_id has been previously memset to zero.
630  */
631 static void sig_pri_party_id_from_ast(struct pri_party_id *pri_id, const struct ast_party_id *ast_id)
632 {
633         int presentation;
634
635         presentation = ast_to_pri_presentation(ast_id->number_presentation);
636         if (!ast_strlen_zero(ast_id->name)) {
637                 pri_id->name.valid = 1;
638                 pri_id->name.presentation = presentation;
639                 pri_id->name.char_set = PRI_CHAR_SET_ISO8859_1;
640                 ast_copy_string(pri_id->name.str, ast_id->name, sizeof(pri_id->name.str));
641         }
642         if (!ast_strlen_zero(ast_id->number)) {
643                 pri_id->number.valid = 1;
644                 pri_id->number.presentation = presentation;
645                 pri_id->number.plan = ast_id->number_type;
646                 ast_copy_string(pri_id->number.str, ast_id->number, sizeof(pri_id->number.str));
647         }
648 #if defined(HAVE_PRI_SUBADDR)
649         sig_pri_party_subaddress_from_ast(&pri_id->subaddress, &ast_id->subaddress);
650 #endif  /* defined(HAVE_PRI_SUBADDR) */
651 }
652
653 /*!
654  * \internal
655  * \brief Update the PRI redirecting information for the current call.
656  * \since 1.8
657  *
658  * \param pvt sig_pri private channel structure.
659  * \param ast Asterisk channel
660  *
661  * \return Nothing
662  *
663  * \note Assumes that the PRI lock is already obtained.
664  */
665 static void sig_pri_redirecting_update(struct sig_pri_chan *pvt, struct ast_channel *ast)
666 {
667         struct pri_party_redirecting pri_redirecting;
668         struct ast_party_redirecting ast_redirecting;
669
670         /* Gather asterisk redirecting data */
671         ast_redirecting = ast->redirecting;
672         ast_redirecting.from.number = ast->cid.cid_rdnis;
673
674 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
675
676         memset(&pri_redirecting, 0, sizeof(pri_redirecting));
677         sig_pri_party_id_from_ast(&pri_redirecting.from, &ast_redirecting.from);
678         sig_pri_party_id_from_ast(&pri_redirecting.to, &ast_redirecting.to);
679         pri_redirecting.count = ast_redirecting.count;
680         pri_redirecting.reason = ast_to_pri_reason(ast_redirecting.reason);
681
682         pri_redirecting_update(pvt->pri->pri, pvt->call, &pri_redirecting);
683 }
684
685 /*!
686  * \internal
687  * \brief Reset DTMF detector.
688  * \since 1.8
689  *
690  * \param p sig_pri channel structure.
691  *
692  * \return Nothing
693  */
694 static void sig_pri_dsp_reset_and_flush_digits(struct sig_pri_chan *p)
695 {
696         if (p->calls->dsp_reset_and_flush_digits) {
697                 p->calls->dsp_reset_and_flush_digits(p->chan_pvt);
698         }
699 }
700
701 static int sig_pri_set_echocanceller(struct sig_pri_chan *p, int enable)
702 {
703         if (p->calls->set_echocanceller)
704                 return p->calls->set_echocanceller(p->chan_pvt, enable);
705         else
706                 return -1;
707 }
708
709 static void sig_pri_fixup_chans(struct sig_pri_chan *old_chan, struct sig_pri_chan *new_chan)
710 {
711         if (old_chan->calls->fixup_chans)
712                 old_chan->calls->fixup_chans(old_chan->chan_pvt, new_chan->chan_pvt);
713 }
714
715 static int sig_pri_play_tone(struct sig_pri_chan *p, enum sig_pri_tone tone)
716 {
717         if (p->calls->play_tone)
718                 return p->calls->play_tone(p->chan_pvt, tone);
719         else
720                 return -1;
721 }
722
723 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)
724 {
725         struct ast_channel *c;
726
727         if (p->calls->new_ast_channel)
728                 c = p->calls->new_ast_channel(p->chan_pvt, state, startpbx, ulaw, transfercapability, exten, requestor);
729         else
730                 return NULL;
731
732         if (!p->owner)
733                 p->owner = c;
734         p->isidlecall = 0;
735         p->alreadyhungup = 0;
736         if (transfercapability & AST_TRANS_CAP_DIGITAL) {
737                 c->transfercapability = transfercapability;
738                 pbx_builtin_setvar_helper(c, "TRANSFERCAPABILITY", ast_transfercapability2str(transfercapability));
739                 sig_pri_set_digital(p, 1);
740         }
741
742         return c;
743 }
744
745 struct ast_channel *sig_pri_request(struct sig_pri_chan *p, enum sig_pri_law law, const struct ast_channel *requestor, int transfercapability)
746 {
747         struct ast_channel *ast;
748
749         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
750
751         p->outgoing = 1;
752         ast = sig_pri_new_ast_channel(p, AST_STATE_RESERVED, 0, law, transfercapability, p->exten, requestor);
753         if (!ast) {
754                 p->outgoing = 0;
755         }
756         return ast;
757 }
758
759 int pri_is_up(struct sig_pri_pri *pri)
760 {
761         int x;
762         for (x = 0; x < NUM_DCHANS; x++) {
763                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
764                         return 1;
765         }
766         return 0;
767 }
768
769 static char *pri_order(int level)
770 {
771         switch (level) {
772         case 0:
773                 return "Primary";
774         case 1:
775                 return "Secondary";
776         case 2:
777                 return "Tertiary";
778         case 3:
779                 return "Quaternary";
780         default:
781                 return "<Unknown>";
782         }
783 }
784
785 /* Returns index of the active dchan */
786 static int pri_active_dchan_index(struct sig_pri_pri *pri)
787 {
788         int x;
789
790         for (x = 0; x < NUM_DCHANS; x++) {
791                 if ((pri->dchans[x] == pri->pri))
792                         return x;
793         }
794
795         ast_log(LOG_WARNING, "No active dchan found!\n");
796         return -1;
797 }
798
799 static int pri_find_dchan(struct sig_pri_pri *pri)
800 {
801         int oldslot = -1;
802         struct pri *old;
803         int newslot = -1;
804         int x;
805         old = pri->pri;
806         for (x = 0; x < NUM_DCHANS; x++) {
807                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
808                         newslot = x;
809                 if (pri->dchans[x] == old) {
810                         oldslot = x;
811                 }
812         }
813         if (newslot < 0) {
814                 newslot = 0;
815                 /* This is annoying to see on non persistent layer 2 connections.  Let's not complain in that case */
816                 if (pri->sig != SIG_BRI_PTMP) {
817                         ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel as D-channel anyway!\n");
818                 }
819         }
820         if (old && (oldslot != newslot))
821                 ast_log(LOG_NOTICE, "Switching from d-channel fd %d to fd %d!\n",
822                         pri->fds[oldslot], pri->fds[newslot]);
823         pri->pri = pri->dchans[newslot];
824         return 0;
825 }
826
827 static void pri_queue_frame(struct sig_pri_chan *p, struct ast_frame *f, struct sig_pri_pri *pri)
828 {
829         /* We must unlock the PRI to avoid the possibility of a deadlock */
830         if (pri)
831                 ast_mutex_unlock(&pri->lock);
832         for (;;) {
833                 if (p->owner) {
834                         if (ast_channel_trylock(p->owner)) {
835                                 PRI_DEADLOCK_AVOIDANCE(p);
836                         } else {
837                                 ast_queue_frame(p->owner, f);
838                                 ast_channel_unlock(p->owner);
839                                 break;
840                         }
841                 } else
842                         break;
843         }
844         if (pri)
845                 ast_mutex_lock(&pri->lock);
846 }
847
848 static void pri_queue_control(struct sig_pri_chan *p, int subclass, struct sig_pri_pri *pri)
849 {
850         struct ast_frame f = {AST_FRAME_CONTROL, };
851
852         if (p->calls->queue_control) {
853                 p->calls->queue_control(p->chan_pvt, subclass);
854         }
855
856         f.subclass.integer = subclass;
857         pri_queue_frame(p, &f, pri);
858 }
859
860 static int pri_find_principle(struct sig_pri_pri *pri, int channel, q931_call *call)
861 {
862         int x;
863         int span;
864         int principle;
865
866         if (channel < 0) {
867                 /* Channel is not picked yet. */
868                 return -1;
869         }
870
871         if (channel & PRI_HELD_CALL) {
872                 if (!call) {
873                         /* Cannot find a held call without a call. */
874                         return -1;
875                 }
876                 principle = -1;
877                 for (x = 0; x < pri->numchans; ++x) {
878                         if (pri->pvts[x]
879                                 && pri->pvts[x]->call == call) {
880                                 principle = x;
881                                 break;
882                         }
883                 }
884                 return principle;
885         }
886
887         span = PRI_SPAN(channel);
888         if (!(channel & PRI_EXPLICIT)) {
889                 int index;
890
891                 index = pri_active_dchan_index(pri);
892                 if (index == -1) {
893                         return -1;
894                 }
895                 span = pri->dchan_logical_span[index];
896         }
897
898         channel = PRI_CHANNEL(channel);
899         principle = -1;
900         for (x = 0; x < pri->numchans; x++) {
901                 if (pri->pvts[x]
902                         && pri->pvts[x]->prioffset == channel
903                         && pri->pvts[x]->logicalspan == span
904                         && !pri->pvts[x]->no_b_channel) {
905                         principle = x;
906                         break;
907                 }
908         }
909
910         return principle;
911 }
912
913 static int pri_fixup_principle(struct sig_pri_pri *pri, int principle, q931_call *call)
914 {
915         int x;
916
917         if (principle < 0 || pri->numchans <= principle) {
918                 /* Out of rannge */
919                 return -1;
920         }
921         if (!call) {
922                 /* No call */
923                 return principle;
924         }
925         if (pri->pvts[principle] && pri->pvts[principle]->call == call) {
926                 /* Call is already on the specified principle. */
927                 return principle;
928         }
929
930         /* Find the old principle location. */
931         for (x = 0; x < pri->numchans; x++) {
932                 struct sig_pri_chan *new_chan;
933                 struct sig_pri_chan *old_chan;
934
935                 if (!pri->pvts[x] || pri->pvts[x]->call != call) {
936                         continue;
937                 }
938
939                 /* Found our call */
940                 new_chan = pri->pvts[principle];
941                 old_chan = pri->pvts[x];
942
943                 ast_verb(3, "Moving call from channel %d to channel %d\n",
944                         old_chan->channel, new_chan->channel);
945                 if (new_chan->owner) {
946                         ast_log(LOG_WARNING,
947                                 "Can't fix up channel from %d to %d because %d is already in use\n",
948                                 old_chan->channel, new_chan->channel, new_chan->channel);
949                         return -1;
950                 }
951
952                 sig_pri_fixup_chans(old_chan, new_chan);
953
954                 /* Fix it all up now */
955                 new_chan->owner = old_chan->owner;
956                 old_chan->owner = NULL;
957
958                 new_chan->call = old_chan->call;
959                 old_chan->call = NULL;
960
961                 /* Transfer flags from the old channel. */
962                 new_chan->alerting = old_chan->alerting;
963                 new_chan->alreadyhungup = old_chan->alreadyhungup;
964                 new_chan->isidlecall = old_chan->isidlecall;
965                 new_chan->proceeding = old_chan->proceeding;
966                 new_chan->progress = old_chan->progress;
967                 new_chan->setup_ack = old_chan->setup_ack;
968                 new_chan->outgoing = old_chan->outgoing;
969                 new_chan->digital = old_chan->digital;
970                 old_chan->alerting = 0;
971                 old_chan->alreadyhungup = 0;
972                 old_chan->isidlecall = 0;
973                 old_chan->proceeding = 0;
974                 old_chan->progress = 0;
975                 old_chan->setup_ack = 0;
976                 old_chan->outgoing = 0;
977                 old_chan->digital = 0;
978
979                 /* More stuff to transfer to the new channel. */
980 #if defined(HAVE_PRI_REVERSE_CHARGE)
981                 new_chan->reverse_charging_indication = old_chan->reverse_charging_indication;
982 #endif  /* defined(HAVE_PRI_REVERSE_CHARGE) */
983 #if defined(HAVE_PRI_SETUP_KEYPAD)
984                 strcpy(new_chan->keypad_digits, old_chan->keypad_digits);
985 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
986
987                 if (new_chan->no_b_channel) {
988                         /* Copy the real channel configuration to the no B channel interface. */
989                         new_chan->hidecallerid = old_chan->hidecallerid;
990                         new_chan->hidecalleridname = old_chan->hidecalleridname;
991                         new_chan->immediate = old_chan->immediate;
992                         new_chan->priexclusive = old_chan->priexclusive;
993                         new_chan->priindication_oob = old_chan->priindication_oob;
994                         new_chan->use_callerid = old_chan->use_callerid;
995                         new_chan->use_callingpres = old_chan->use_callingpres;
996                         new_chan->stripmsd = old_chan->stripmsd;
997                         strcpy(new_chan->context, old_chan->context);
998                         strcpy(new_chan->mohinterpret, old_chan->mohinterpret);
999
1000                         /* Become a member of the old channel span/trunk-group. */
1001                         new_chan->logicalspan = old_chan->logicalspan;
1002                         new_chan->mastertrunkgroup = old_chan->mastertrunkgroup;
1003                 }
1004
1005                 return principle;
1006         }
1007         ast_log(LOG_WARNING, "Call specified, but not found?\n");
1008         return -1;
1009 }
1010
1011 static char * redirectingreason2str(int redirectingreason)
1012 {
1013         switch (redirectingreason) {
1014         case 0:
1015                 return "UNKNOWN";
1016         case 1:
1017                 return "BUSY";
1018         case 2:
1019                 return "NO_REPLY";
1020         case 0xF:
1021                 return "UNCONDITIONAL";
1022         default:
1023                 return "NOREDIRECT";
1024         }
1025 }
1026
1027 static char *dialplan2str(int dialplan)
1028 {
1029         if (dialplan == -1) {
1030                 return("Dynamically set dialplan in ISDN");
1031         }
1032         return (pri_plan2str(dialplan));
1033 }
1034
1035 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_pri *pri, const char *number, const int plan)
1036 {
1037         switch (plan) {
1038         case PRI_INTERNATIONAL_ISDN:            /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
1039                 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
1040                 break;
1041         case PRI_NATIONAL_ISDN:                 /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
1042                 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
1043                 break;
1044         case PRI_LOCAL_ISDN:                    /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
1045                 snprintf(buf, size, "%s%s", pri->localprefix, number);
1046                 break;
1047         case PRI_PRIVATE:                       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
1048                 snprintf(buf, size, "%s%s", pri->privateprefix, number);
1049                 break;
1050         case PRI_UNKNOWN:                       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
1051                 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
1052                 break;
1053         default:                                /* other Q.931 dialplan => don't twiddle with callingnum */
1054                 snprintf(buf, size, "%s", number);
1055                 break;
1056         }
1057 }
1058
1059 /*! \note Assumes the pri->lock is already obtained. */
1060 static int pri_check_restart(struct sig_pri_pri *pri)
1061 {
1062 #ifdef HAVE_PRI_SERVICE_MESSAGES
1063 tryanotherpos:
1064 #endif
1065         do {
1066                 pri->resetpos++;
1067         } while (pri->resetpos < pri->numchans
1068                 && (!pri->pvts[pri->resetpos]
1069                         || pri->pvts[pri->resetpos]->no_b_channel
1070                         || pri->pvts[pri->resetpos]->call
1071                         || pri->pvts[pri->resetpos]->resetting));
1072         if (pri->resetpos < pri->numchans) {
1073 #ifdef HAVE_PRI_SERVICE_MESSAGES
1074                 char db_chan_name[20], db_answer[5], state;
1075                 int why;
1076
1077                 /* check if the channel is out of service */
1078                 snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->span, pri->pvts[pri->resetpos]->channel);
1079
1080                 /* if so, try next channel */
1081                 if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
1082                         sscanf(db_answer, "%1c:%30d", &state, &why);
1083                         if (why) {
1084                                 ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), not sending RESTART\n", pri->span,
1085                                         pri->pvts[pri->resetpos]->channel, (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
1086                                 goto tryanotherpos;
1087                         }
1088                 }
1089 #endif
1090
1091                 /* Mark the channel as resetting and restart it */
1092                 pri->pvts[pri->resetpos]->resetting = 1;
1093                 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
1094         } else {
1095                 pri->resetting = 0;
1096                 time(&pri->lastreset);
1097         }
1098         return 0;
1099 }
1100
1101 static int pri_find_empty_chan(struct sig_pri_pri *pri, int backwards)
1102 {
1103         int x;
1104         if (backwards)
1105                 x = pri->numchans;
1106         else
1107                 x = 0;
1108         for (;;) {
1109                 if (backwards && (x < 0))
1110                         break;
1111                 if (!backwards && (x >= pri->numchans))
1112                         break;
1113                 if (pri->pvts[x]
1114                         && !pri->pvts[x]->no_b_channel
1115                         && !pri->pvts[x]->inalarm
1116                         && !pri->pvts[x]->owner) {
1117                         ast_debug(1, "Found empty available channel %d/%d\n",
1118                                 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
1119                         return x;
1120                 }
1121                 if (backwards)
1122                         x--;
1123                 else
1124                         x++;
1125         }
1126         return -1;
1127 }
1128
1129 #if defined(HAVE_PRI_CALL_HOLD)
1130 /*!
1131  * \internal
1132  * \brief Find or create an empty no-B-channel interface to use.
1133  * \since 1.8
1134  *
1135  * \param pri sig_pri span controller to find interface.
1136  *
1137  * \note Assumes the pri->lock is already obtained.
1138  *
1139  * \retval array-index into private pointer array on success.
1140  * \retval -1 on error.
1141  */
1142 static int pri_find_empty_nobch(struct sig_pri_pri *pri)
1143 {
1144         int idx;
1145
1146         for (idx = 0; idx < pri->numchans; ++idx) {
1147                 if (pri->pvts[idx]
1148                         && pri->pvts[idx]->no_b_channel
1149                         && !pri->pvts[idx]->inalarm
1150                         && !pri->pvts[idx]->owner) {
1151                         ast_debug(1, "Found empty available no B channel interface\n");
1152                         return idx;
1153                 }
1154         }
1155
1156         /* Need to create a new interface. */
1157         if (pri->calls->new_nobch_intf) {
1158                 idx = pri->calls->new_nobch_intf(pri);
1159         } else {
1160                 idx = -1;
1161         }
1162         return idx;
1163 }
1164 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1165
1166 #if defined(HAVE_PRI_CALL_HOLD)
1167 /*!
1168  * \internal
1169  * \brief Find the channel associated with the libpri call.
1170  * \since 1.8
1171  *
1172  * \param pri sig_pri span controller to find interface.
1173  * \param call LibPRI opaque call pointer to find.
1174  *
1175  * \note Assumes the pri->lock is already obtained.
1176  *
1177  * \retval array-index into private pointer array on success.
1178  * \retval -1 on error.
1179  */
1180 static int pri_find_pri_call(struct sig_pri_pri *pri, q931_call *call)
1181 {
1182         int idx;
1183
1184         for (idx = 0; idx < pri->numchans; ++idx) {
1185                 if (pri->pvts[idx] && pri->pvts[idx]->call == call) {
1186                         /* Found the channel */
1187                         return idx;
1188                 }
1189         }
1190         return -1;
1191 }
1192 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1193
1194 static void *do_idle_thread(void *v_pvt)
1195 {
1196         struct sig_pri_chan *pvt = v_pvt;
1197         struct ast_channel *chan = pvt->owner;
1198         struct ast_frame *f;
1199         char ex[80];
1200         /* Wait up to 30 seconds for an answer */
1201         int newms, ms = 30000;
1202
1203         ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
1204         snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
1205         if (ast_call(chan, ex, 0)) {
1206                 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
1207                 ast_hangup(chan);
1208                 return NULL;
1209         }
1210         while ((newms = ast_waitfor(chan, ms)) > 0) {
1211                 f = ast_read(chan);
1212                 if (!f) {
1213                         /* Got hangup */
1214                         break;
1215                 }
1216                 if (f->frametype == AST_FRAME_CONTROL) {
1217                         switch (f->subclass.integer) {
1218                         case AST_CONTROL_ANSWER:
1219                                 /* Launch the PBX */
1220                                 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
1221                                 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
1222                                 chan->priority = 1;
1223                                 ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
1224                                 ast_pbx_run(chan);
1225                                 /* It's already hungup, return immediately */
1226                                 return NULL;
1227                         case AST_CONTROL_BUSY:
1228                                 ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
1229                                 break;
1230                         case AST_CONTROL_CONGESTION:
1231                                 ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
1232                                 break;
1233                         };
1234                 }
1235                 ast_frfree(f);
1236                 ms = newms;
1237         }
1238         /* Hangup the channel since nothing happend */
1239         ast_hangup(chan);
1240         return NULL;
1241 }
1242
1243 static void *pri_ss_thread(void *data)
1244 {
1245         struct sig_pri_chan *p = data;
1246         struct ast_channel *chan = p->owner;
1247         char exten[AST_MAX_EXTENSION];
1248         int res;
1249         int len;
1250         int timeout;
1251
1252         if (!chan) {
1253                 /* We lost the owner before we could get started. */
1254                 return NULL;
1255         }
1256
1257         /*
1258          * In the bizarre case where the channel has become a zombie before we
1259          * even get started here, abort safely.
1260          */
1261         if (!chan->tech_pvt) {
1262                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
1263                 ast_hangup(chan);
1264                 return NULL;
1265         }
1266
1267         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
1268
1269         sig_pri_dsp_reset_and_flush_digits(p);
1270
1271         /* Now loop looking for an extension */
1272         ast_copy_string(exten, p->exten, sizeof(exten));
1273         len = strlen(exten);
1274         res = 0;
1275         while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
1276                 if (len && !ast_ignore_pattern(chan->context, exten))
1277                         sig_pri_play_tone(p, -1);
1278                 else
1279                         sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
1280                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
1281                         timeout = pri_matchdigittimeout;
1282                 else
1283                         timeout = pri_gendigittimeout;
1284                 res = ast_waitfordigit(chan, timeout);
1285                 if (res < 0) {
1286                         ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
1287                         ast_hangup(chan);
1288                         return NULL;
1289                 } else if (res) {
1290                         exten[len++] = res;
1291                         exten[len] = '\0';
1292                 } else
1293                         goto exit;
1294         }
1295         /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
1296         if (ast_strlen_zero(exten)) {
1297                 ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
1298                 exten[0] = 's';
1299                 exten[1] = '\0';
1300         } else {
1301                 if (chan->cid.cid_dnid) {
1302                         ast_free(chan->cid.cid_dnid);
1303                 }
1304                 chan->cid.cid_dnid = ast_strdup(exten);
1305         }
1306         sig_pri_play_tone(p, -1);
1307         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
1308                 /* Start the real PBX */
1309                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1310                 sig_pri_dsp_reset_and_flush_digits(p);
1311                 if (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) {
1312                         if (p->pri->pri) {              
1313                                 if (!pri_grab(p, p->pri)) {
1314                                         pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
1315                                         p->proceeding = 1;
1316                                         pri_rel(p->pri);
1317                                 } else {
1318                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
1319                                 }
1320                         }
1321                 }
1322
1323                 sig_pri_set_echocanceller(p, 1);
1324                 ast_setstate(chan, AST_STATE_RING);
1325                 res = ast_pbx_run(chan);
1326                 if (res) {
1327                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
1328                 }
1329         } else {
1330                 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
1331                 chan->hangupcause = AST_CAUSE_UNALLOCATED;
1332                 ast_hangup(chan);
1333                 p->exten[0] = '\0';
1334                 /* Since we send release complete here, we won't get one */
1335                 p->call = NULL;
1336         }
1337         return NULL;
1338
1339 exit:
1340         res = sig_pri_play_tone(p, SIG_PRI_TONE_CONGESTION);
1341         if (res < 0)
1342                 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
1343         ast_hangup(chan);
1344         return NULL;
1345 }
1346
1347 void pri_event_alarm(struct sig_pri_pri *pri, int index, int before_start_pri)
1348 {
1349         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
1350         if (!before_start_pri)
1351                 pri_find_dchan(pri);
1352 }
1353
1354 void pri_event_noalarm(struct sig_pri_pri *pri, int index, int before_start_pri)
1355 {
1356         pri->dchanavail[index] |= DCHAN_NOTINALARM;
1357         if (!before_start_pri)
1358                 pri_restart(pri->dchans[index]);
1359 }
1360
1361 /*!
1362  * \internal
1363  * \brief Convert libpri party id into asterisk party id.
1364  * \since 1.8
1365  *
1366  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
1367  * \param pri_id libpri party id structure containing source information.
1368  * \param pri Span controlling structure.
1369  *
1370  * \note The filled in ast_id structure needs to be destroyed by
1371  * ast_party_id_free() when it is no longer needed.
1372  *
1373  * \return Nothing
1374  */
1375 static void sig_pri_party_id_convert(struct ast_party_id *ast_id,
1376         const struct pri_party_id *pri_id, struct sig_pri_pri *pri)
1377 {
1378         char number[AST_MAX_EXTENSION];
1379
1380         if (pri_id->name.valid) {
1381                 ast_id->name = ast_strdup(pri_id->name.str);
1382         }
1383         if (pri_id->number.valid) {
1384                 apply_plan_to_number(number, sizeof(number), pri, pri_id->number.str,
1385                         pri_id->number.plan);
1386                 ast_id->number = ast_strdup(number);
1387                 ast_id->number_type = pri_id->number.plan;
1388         }
1389         if (pri_id->name.valid || pri_id->number.valid) {
1390                 ast_id->number_presentation = overall_ast_presentation(pri_id);
1391         }
1392 #if defined(HAVE_PRI_SUBADDR)
1393         if (pri_id->subaddress.valid) {
1394                 sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
1395         }
1396 #endif  /* defined(HAVE_PRI_SUBADDR) */
1397 }
1398
1399 /*!
1400  * \internal
1401  * \brief Convert libpri redirecting information into asterisk redirecting information.
1402  * \since 1.8
1403  *
1404  * \param ast_redirecting Asterisk redirecting structure to fill.
1405  * \param pri_redirecting libpri redirecting structure containing source information.
1406  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
1407  * \param pri Span controlling structure.
1408  *
1409  * \note The filled in ast_redirecting structure needs to be destroyed by
1410  * ast_party_redirecting_free() when it is no longer needed.
1411  *
1412  * \return Nothing
1413  */
1414 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
1415         const struct pri_party_redirecting *pri_redirecting,
1416         const struct ast_party_redirecting *ast_guide,
1417         struct sig_pri_pri *pri)
1418 {
1419         ast_party_redirecting_set_init(ast_redirecting, ast_guide);
1420
1421         sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
1422         sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
1423         ast_redirecting->count = pri_redirecting->count;
1424         ast_redirecting->reason = pri_to_ast_reason(pri_redirecting->reason);
1425 }
1426
1427 /*!
1428  * \internal
1429  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
1430  * \since 1.8
1431  *
1432  * \param msn_patterns Comma separated list of MSN patterns to match.
1433  * \param exten Extension to match in the MSN list.
1434  *
1435  * \retval 1 if matches.
1436  * \retval 0 if no match.
1437  */
1438 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
1439 {
1440         char *pattern;
1441         char *msn_list;
1442         char *list_tail;
1443
1444         msn_list = strdupa(msn_patterns);
1445
1446         list_tail = NULL;
1447         pattern = strtok_r(msn_list, ",", &list_tail);
1448         while (pattern) {
1449                 pattern = ast_strip(pattern);
1450                 if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
1451                         /* Extension matched the pattern. */
1452                         return 1;
1453                 }
1454                 pattern = strtok_r(NULL, ",", &list_tail);
1455         }
1456         /* Did not match any pattern in the list. */
1457         return 0;
1458 }
1459
1460 /*!
1461  * \internal
1462  * \brief Obtain the sig_pri owner channel lock if the owner exists.
1463  * \since 1.8
1464  *
1465  * \param pri sig_pri PRI control structure.
1466  * \param chanpos Channel position in the span.
1467  *
1468  * \note Assumes the pri->lock is already obtained.
1469  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1470  *
1471  * \return Nothing
1472  */
1473 static void sig_pri_lock_owner(struct sig_pri_pri *pri, int chanpos)
1474 {
1475         for (;;) {
1476                 if (!pri->pvts[chanpos]->owner) {
1477                         /* There is no owner lock to get. */
1478                         break;
1479                 }
1480                 if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
1481                         /* We got the lock */
1482                         break;
1483                 }
1484                 /* We must unlock the PRI to avoid the possibility of a deadlock */
1485                 ast_mutex_unlock(&pri->lock);
1486                 PRI_DEADLOCK_AVOIDANCE(pri->pvts[chanpos]);
1487                 ast_mutex_lock(&pri->lock);
1488         }
1489 }
1490
1491 /*!
1492  * \internal
1493  * \brief Handle the call associated PRI subcommand events.
1494  * \since 1.8
1495  *
1496  * \param pri sig_pri PRI control structure.
1497  * \param chanpos Channel position in the span.
1498  * \param event_id PRI event id
1499  * \param channel PRI encoded span/channel
1500  * \param subcmds Subcommands to process if any. (Could be NULL).
1501  * \param call_rsp libpri opaque call structure to send any responses toward.
1502  * Could be NULL either because it is not available or the call is for the
1503  * dummy call reference.  However, this should not be NULL in the cases that
1504  * need to use the pointer to send a response message back.
1505  *
1506  * \note Assumes the pri->lock is already obtained.
1507  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1508  *
1509  * \return Nothing
1510  */
1511 static void sig_pri_handle_subcmds(struct sig_pri_pri *pri, int chanpos, int event_id,
1512         int channel, const struct pri_subcommands *subcmds, q931_call *call_rsp)
1513 {
1514         int index;
1515         struct ast_channel *owner;
1516         struct ast_party_redirecting ast_redirecting;
1517
1518         if (!subcmds) {
1519                 return;
1520         }
1521         for (index = 0; index < subcmds->counter_subcmd; ++index) {
1522                 const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
1523
1524                 switch (subcmd->cmd) {
1525                 case PRI_SUBCMD_CONNECTED_LINE:
1526                         sig_pri_lock_owner(pri, chanpos);
1527                         owner = pri->pvts[chanpos]->owner;
1528                         if (owner) {
1529                                 struct ast_party_connected_line ast_connected;
1530                                 int caller_id_update;
1531
1532                                 /* Extract the connected line information */
1533                                 ast_party_connected_line_init(&ast_connected);
1534                                 sig_pri_party_id_convert(&ast_connected.id, &subcmd->u.connected_line.id,
1535                                         pri);
1536
1537                                 caller_id_update = 0;
1538                                 if (ast_connected.id.name) {
1539                                         /* Save name for Caller-ID update */
1540                                         ast_copy_string(pri->pvts[chanpos]->cid_name,
1541                                                 ast_connected.id.name, sizeof(pri->pvts[chanpos]->cid_name));
1542                                         caller_id_update = 1;
1543                                 }
1544                                 if (ast_connected.id.number) {
1545                                         /* Save number for Caller-ID update */
1546                                         ast_copy_string(pri->pvts[chanpos]->cid_num, ast_connected.id.number,
1547                                                 sizeof(pri->pvts[chanpos]->cid_num));
1548                                         pri->pvts[chanpos]->cid_ton = ast_connected.id.number_type;
1549                                         caller_id_update = 1;
1550                                 } else {
1551                                         ast_connected.id.number = ast_strdup("");
1552                                 }
1553                                 ast_connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1554
1555                                 pri->pvts[chanpos]->cid_subaddr[0] = '\0';
1556 #if defined(HAVE_PRI_SUBADDR)
1557                                 if (ast_connected.id.subaddress.valid) {
1558                                         ast_party_subaddress_set(&owner->cid.subaddress,
1559                                                 &ast_connected.id.subaddress);
1560                                         if (ast_connected.id.subaddress.str) {
1561                                                 ast_copy_string(pri->pvts[chanpos]->cid_subaddr,
1562                                                         ast_connected.id.subaddress.str,
1563                                                         sizeof(pri->pvts[chanpos]->cid_subaddr));
1564                                         }
1565                                 }
1566 #endif  /* defined(HAVE_PRI_SUBADDR) */
1567                                 if (caller_id_update) {
1568                                         pri->pvts[chanpos]->callingpres =
1569                                                 ast_connected.id.number_presentation;
1570                                         sig_pri_set_caller_id(pri->pvts[chanpos]);
1571                                         ast_set_callerid(owner, S_OR(ast_connected.id.number, NULL),
1572                                                 S_OR(ast_connected.id.name, NULL),
1573                                                 S_OR(ast_connected.id.number, NULL));
1574                                 }
1575
1576                                 /* Update the connected line information on the other channel */
1577                                 if (event_id != PRI_EVENT_RING) {
1578                                         /* This connected_line update was not from a SETUP message. */
1579                                         ast_channel_queue_connected_line_update(owner, &ast_connected);
1580                                 }
1581
1582                                 ast_party_connected_line_free(&ast_connected);
1583                                 ast_channel_unlock(owner);
1584                         }
1585                         break;
1586                 case PRI_SUBCMD_REDIRECTING:
1587                         sig_pri_lock_owner(pri, chanpos);
1588                         owner = pri->pvts[chanpos]->owner;
1589                         if (owner) {
1590                                 sig_pri_redirecting_convert(&ast_redirecting, &subcmd->u.redirecting,
1591                                         &owner->redirecting, pri);
1592
1593 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
1594
1595                                 ast_channel_set_redirecting(owner, &ast_redirecting);
1596                                 if (event_id != PRI_EVENT_RING) {
1597                                         /* This redirection was not from a SETUP message. */
1598                                         ast_channel_queue_redirecting_update(owner, &ast_redirecting);
1599                                 }
1600                                 ast_party_redirecting_free(&ast_redirecting);
1601
1602                                 ast_channel_unlock(owner);
1603                         }
1604                         break;
1605 #if defined(HAVE_PRI_CALL_REROUTING)
1606                 case PRI_SUBCMD_REROUTING:
1607                         sig_pri_lock_owner(pri, chanpos);
1608                         owner = pri->pvts[chanpos]->owner;
1609                         if (owner) {
1610                                 struct pri_party_redirecting pri_deflection;
1611
1612                                 if (!call_rsp) {
1613                                         ast_channel_unlock(owner);
1614                                         ast_log(LOG_WARNING,
1615                                                 "CallRerouting/CallDeflection to '%s' without call!\n",
1616                                                 subcmd->u.rerouting.deflection.to.number.str);
1617                                         break;
1618                                 }
1619
1620                                 pri_deflection = subcmd->u.rerouting.deflection;
1621
1622                                 ast_string_field_set(owner, call_forward, pri_deflection.to.number.str);
1623
1624                                 /* Adjust the deflecting to number based upon the subscription option. */
1625                                 switch (subcmd->u.rerouting.subscription_option) {
1626                                 case 0: /* noNotification */
1627                                 case 1: /* notificationWithoutDivertedToNr */
1628                                         /* Delete the number because the far end is not supposed to see it. */
1629                                         pri_deflection.to.number.presentation =
1630                                                 PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
1631                                         pri_deflection.to.number.plan =
1632                                                 (PRI_TON_UNKNOWN << 4) | PRI_NPI_E163_E164;
1633                                         pri_deflection.to.number.str[0] = '\0';
1634                                         break;
1635                                 case 2: /* notificationWithDivertedToNr */
1636                                         break;
1637                                 case 3: /* notApplicable */
1638                                 default:
1639                                         break;
1640                                 }
1641                                 sig_pri_redirecting_convert(&ast_redirecting, &pri_deflection,
1642                                         &owner->redirecting, pri);
1643                                 ast_channel_set_redirecting(owner, &ast_redirecting);
1644                                 ast_party_redirecting_free(&ast_redirecting);
1645
1646                                 /*
1647                                  * Send back positive ACK to CallRerouting/CallDeflection.
1648                                  *
1649                                  * Note:  This call will be hungup by the dial application when
1650                                  * it processes the call_forward string set above.
1651                                  */
1652                                 pri_rerouting_rsp(pri->pri, call_rsp, subcmd->u.rerouting.invoke_id,
1653                                         PRI_REROUTING_RSP_OK_CLEAR);
1654
1655                                 /* This line is BUSY to further attempts by this dialing attempt. */
1656                                 ast_queue_control(owner, AST_CONTROL_BUSY);
1657
1658                                 ast_channel_unlock(owner);
1659                         }
1660                         break;
1661 #endif  /* defined(HAVE_PRI_CALL_REROUTING) */
1662                 default:
1663                         ast_debug(2,
1664                                 "Unknown call subcommand(%d) in %s event on channel %d/%d on span %d.\n",
1665                                 subcmd->cmd, pri_event2str(event_id), PRI_SPAN(channel),
1666                                 PRI_CHANNEL(channel), pri->span);
1667                         break;
1668                 }
1669         }
1670 }
1671
1672 #if defined(HAVE_PRI_CALL_HOLD)
1673 /*!
1674  * \internal
1675  * \brief Attempt to transfer the active call to the held call.
1676  * \since 1.8
1677  *
1678  * \param pri sig_pri PRI control structure.
1679  * \param active_call Active call to transfer.
1680  * \param held_call Held call to transfer.
1681  *
1682  * \note Assumes the pri->lock is already obtained.
1683  *
1684  * \retval 0 on success.
1685  * \retval -1 on error.
1686  */
1687 static int sig_pri_attempt_transfer(struct sig_pri_pri *pri, q931_call *active_call, q931_call *held_call)
1688 {
1689         int retval;
1690         int active_chanpos;
1691         int held_chanpos;
1692         struct ast_channel *active_ast;
1693         struct ast_channel *held_ast;
1694         struct ast_channel *bridged;
1695
1696         active_chanpos = pri_find_pri_call(pri, active_call);
1697         held_chanpos = pri_find_pri_call(pri, held_call);
1698         if (active_chanpos < 0 || held_chanpos < 0) {
1699                 return -1;
1700         }
1701
1702         sig_pri_lock_private(pri->pvts[active_chanpos]);
1703         sig_pri_lock_private(pri->pvts[held_chanpos]);
1704         sig_pri_lock_owner(pri, active_chanpos);
1705         sig_pri_lock_owner(pri, held_chanpos);
1706
1707         active_ast = pri->pvts[active_chanpos]->owner;
1708         held_ast = pri->pvts[held_chanpos]->owner;
1709         if (!active_ast || !held_ast) {
1710                 if (active_ast) {
1711                         ast_channel_unlock(active_ast);
1712                 }
1713                 if (held_ast) {
1714                         ast_channel_unlock(held_ast);
1715                 }
1716                 sig_pri_unlock_private(pri->pvts[active_chanpos]);
1717                 sig_pri_unlock_private(pri->pvts[held_chanpos]);
1718                 return -1;
1719         }
1720
1721         bridged = ast_bridged_channel(held_ast);
1722         if (bridged) {
1723                 ast_queue_control(held_ast, AST_CONTROL_UNHOLD);
1724
1725                 ast_verb(3, "TRANSFERRING %s to %s\n", held_ast->name, active_ast->name);
1726                 retval = ast_channel_masquerade(active_ast, bridged);
1727         } else {
1728                 /*
1729                  * Could not transfer.  Held channel is not bridged anymore.
1730                  * Held party probably got tired of waiting and hung up.
1731                  */
1732                 retval = -1;
1733         }
1734
1735         ast_channel_unlock(active_ast);
1736         ast_channel_unlock(held_ast);
1737         sig_pri_unlock_private(pri->pvts[active_chanpos]);
1738         sig_pri_unlock_private(pri->pvts[held_chanpos]);
1739
1740         return retval;
1741 }
1742 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1743
1744 #if defined(HAVE_PRI_CALL_HOLD)
1745 /*!
1746  * \internal
1747  * \brief Handle the hold event from libpri.
1748  * \since 1.8
1749  *
1750  * \param pri sig_pri PRI control structure.
1751  * \param ev Hold event received.
1752  *
1753  * \note Assumes the pri->lock is already obtained.
1754  *
1755  * \retval 0 on success.
1756  * \retval -1 on error.
1757  */
1758 static int sig_pri_handle_hold(struct sig_pri_pri *pri, pri_event *ev)
1759 {
1760         int retval;
1761         int chanpos_old;
1762         int chanpos_new;
1763         struct ast_channel *bridged;
1764         struct ast_channel *owner;
1765
1766         chanpos_old = pri_find_principle(pri, ev->hold.channel, ev->hold.call);
1767         if (chanpos_old < 0) {
1768                 ast_log(LOG_WARNING,
1769                         "Received HOLD on unconfigured channel %d/%d span %d\n",
1770                         PRI_SPAN(ev->hold.channel), PRI_CHANNEL(ev->hold.channel), pri->span);
1771                 return -1;
1772         }
1773         if (pri->pvts[chanpos_old]->no_b_channel) {
1774                 /* Call is already on hold or is call waiting call. */
1775                 return -1;
1776         }
1777
1778         sig_pri_lock_private(pri->pvts[chanpos_old]);
1779         sig_pri_lock_owner(pri, chanpos_old);
1780         owner = pri->pvts[chanpos_old]->owner;
1781         if (!owner) {
1782                 retval = -1;
1783                 goto done_with_private;
1784         }
1785         bridged = ast_bridged_channel(owner);
1786         if (!bridged) {
1787                 /* Cannot hold a call that is not bridged. */
1788                 retval = -1;
1789                 goto done_with_owner;
1790         }
1791         chanpos_new = pri_find_empty_nobch(pri);
1792         if (chanpos_new < 0) {
1793                 /* No hold channel available. */
1794                 retval = -1;
1795                 goto done_with_owner;
1796         }
1797         sig_pri_handle_subcmds(pri, chanpos_old, ev->e, ev->hold.channel, ev->hold.subcmds,
1798                 ev->hold.call);
1799         chanpos_new = pri_fixup_principle(pri, chanpos_new, ev->hold.call);
1800         if (chanpos_new < 0) {
1801                 /* Should never happen. */
1802                 retval = -1;
1803         } else {
1804                 struct ast_frame f = { AST_FRAME_CONTROL, };
1805
1806                 f.subclass.integer = AST_CONTROL_HOLD;
1807                 ast_queue_frame(owner, &f);
1808                 retval = 0;
1809         }
1810
1811 done_with_owner:;
1812         ast_channel_unlock(owner);
1813 done_with_private:;
1814         sig_pri_unlock_private(pri->pvts[chanpos_old]);
1815
1816         return retval;
1817 }
1818 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1819
1820 #if defined(HAVE_PRI_CALL_HOLD)
1821 /*!
1822  * \internal
1823  * \brief Handle the retrieve event from libpri.
1824  * \since 1.8
1825  *
1826  * \param pri sig_pri PRI control structure.
1827  * \param ev Retrieve event received.
1828  *
1829  * \note Assumes the pri->lock is already obtained.
1830  *
1831  * \return Nothing
1832  */
1833 static void sig_pri_handle_retrieve(struct sig_pri_pri *pri, pri_event *ev)
1834 {
1835         int chanpos;
1836
1837         if (!(ev->retrieve.channel & PRI_HELD_CALL)
1838                 || pri_find_principle(pri, ev->retrieve.channel, ev->retrieve.call) < 0) {
1839                 /* The call is not currently held. */
1840                 pri_retrieve_rej(pri->pri, ev->retrieve.call,
1841                         PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED);
1842                 return;
1843         }
1844         if (PRI_CHANNEL(ev->retrieve.channel) == 0xFF) {
1845                 chanpos = pri_find_empty_chan(pri, 1);
1846         } else {
1847                 chanpos = pri_find_principle(pri,
1848                         ev->retrieve.channel & ~PRI_HELD_CALL, ev->retrieve.call);
1849                 if (ev->retrieve.flexible
1850                         && (chanpos < 0 || pri->pvts[chanpos]->owner)) {
1851                         /*
1852                          * Channel selection is flexible and the requested channel
1853                          * is bad or already in use.  Pick another channel.
1854                          */
1855                         chanpos = pri_find_empty_chan(pri, 1);
1856                 }
1857         }
1858         if (chanpos < 0) {
1859                 pri_retrieve_rej(pri->pri, ev->retrieve.call,
1860                         ev->retrieve.flexible ? PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION
1861                         : PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
1862                 return;
1863         }
1864         chanpos = pri_fixup_principle(pri, chanpos, ev->retrieve.call);
1865         if (chanpos < 0) {
1866                 /* Channel is already in use. */
1867                 pri_retrieve_rej(pri->pri, ev->retrieve.call,
1868                         PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
1869                 return;
1870         }
1871         sig_pri_lock_private(pri->pvts[chanpos]);
1872         sig_pri_handle_subcmds(pri, chanpos, ev->e, ev->retrieve.channel,
1873                 ev->retrieve.subcmds, ev->retrieve.call);
1874         {
1875                 struct ast_frame f = { AST_FRAME_CONTROL, };
1876
1877                 f.subclass.integer = AST_CONTROL_UNHOLD;
1878                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1879         }
1880         sig_pri_unlock_private(pri->pvts[chanpos]);
1881         pri_retrieve_ack(pri->pri, ev->retrieve.call,
1882                 PVT_TO_CHANNEL(pri->pvts[chanpos]));
1883 }
1884 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1885
1886 static void *pri_dchannel(void *vpri)
1887 {
1888         struct sig_pri_pri *pri = vpri;
1889         pri_event *e;
1890         struct pollfd fds[NUM_DCHANS];
1891         int res;
1892         int chanpos = 0;
1893         int x;
1894         struct ast_channel *c;
1895         struct timeval tv, lowest, *next;
1896         int doidling=0;
1897         char *cc;
1898         time_t t;
1899         int i, which=-1;
1900         int numdchans;
1901         pthread_t threadid;
1902         char ani2str[6];
1903         char plancallingnum[AST_MAX_EXTENSION];
1904         char plancallingani[AST_MAX_EXTENSION];
1905         char calledtonstr[10];
1906         struct timeval lastidle = { 0, 0 };
1907         pthread_t p;
1908         struct ast_channel *idle;
1909         char idlen[80];
1910         int nextidle = -1;
1911         int haveidles;
1912         int activeidles;
1913
1914         gettimeofday(&lastidle, NULL);
1915         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
1916
1917         if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
1918                 /* Need to do idle dialing, check to be sure though */
1919                 cc = strchr(pri->idleext, '@');
1920                 if (cc) {
1921                         *cc = '\0';
1922                         cc++;
1923                         ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
1924 #if 0
1925                         /* Extensions may not be loaded yet */
1926                         if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
1927                                 ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
1928                         else
1929 #endif
1930                                 doidling = 1;
1931                 } else
1932                         ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
1933         }
1934         for (;;) {
1935                 for (i = 0; i < NUM_DCHANS; i++) {
1936                         if (!pri->dchans[i])
1937                                 break;
1938                         fds[i].fd = pri->fds[i];
1939                         fds[i].events = POLLIN | POLLPRI;
1940                         fds[i].revents = 0;
1941                 }
1942                 numdchans = i;
1943                 time(&t);
1944                 ast_mutex_lock(&pri->lock);
1945                 if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->sig != SIG_BRI_PTMP) && (pri->resetinterval > 0)) {
1946                         if (pri->resetting && pri_is_up(pri)) {
1947                                 if (pri->resetpos < 0)
1948                                         pri_check_restart(pri);
1949                         } else {
1950                                 if (!pri->resetting     && (t - pri->lastreset) >= pri->resetinterval) {
1951                                         pri->resetting = 1;
1952                                         pri->resetpos = -1;
1953                                 }
1954                         }
1955                 }
1956                 /* Look for any idle channels if appropriate */
1957                 if (doidling && pri_is_up(pri)) {
1958                         nextidle = -1;
1959                         haveidles = 0;
1960                         activeidles = 0;
1961                         for (x = pri->numchans; x >= 0; x--) {
1962                                 if (pri->pvts[x]
1963                                         && !pri->pvts[x]->owner
1964                                         && !pri->pvts[x]->call
1965                                         && !pri->pvts[x]->no_b_channel) {
1966                                         if (haveidles < pri->minunused) {
1967                                                 haveidles++;
1968                                         } else if (!pri->pvts[x]->resetting) {
1969                                                 nextidle = x;
1970                                                 break;
1971                                         }
1972                                 } else if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall)
1973                                         activeidles++;
1974                         }
1975                         if (nextidle > -1) {
1976                                 if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
1977                                         /* Don't create a new idle call more than once per second */
1978                                         snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
1979                                         idle = sig_pri_request(pri->pvts[nextidle], AST_FORMAT_ULAW, NULL, 0);
1980                                         if (idle) {
1981                                                 pri->pvts[nextidle]->isidlecall = 1;
1982                                                 if (ast_pthread_create_background(&p, NULL, do_idle_thread, pri->pvts[nextidle])) {
1983                                                         ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
1984                                                         ast_hangup(idle);
1985                                                 }
1986                                         } else
1987                                                 ast_log(LOG_WARNING, "Unable to request channel 'DAHDI/%s' for idle call\n", idlen);
1988                                         gettimeofday(&lastidle, NULL);
1989                                 }
1990                         } else if ((haveidles < pri->minunused) &&
1991                                 (activeidles > pri->minidle)) {
1992                                 /* Mark something for hangup if there is something
1993                                    that can be hungup */
1994                                 for (x = pri->numchans; x >= 0; x--) {
1995                                         /* find a candidate channel */
1996                                         if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
1997                                                 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1998                                                 haveidles++;
1999                                                 /* Stop if we have enough idle channels or
2000                                                   can't spare any more active idle ones */
2001                                                 if ((haveidles >= pri->minunused) ||
2002                                                         (activeidles <= pri->minidle))
2003                                                         break;
2004                                         }
2005                                 }
2006                         }
2007                 }
2008                 /* Start with reasonable max */
2009                 lowest = ast_tv(60, 0);
2010                 for (i = 0; i < NUM_DCHANS; i++) {
2011                         /* Find lowest available d-channel */
2012                         if (!pri->dchans[i])
2013                                 break;
2014                         if ((next = pri_schedule_next(pri->dchans[i]))) {
2015                                 /* We need relative time here */
2016                                 tv = ast_tvsub(*next, ast_tvnow());
2017                                 if (tv.tv_sec < 0) {
2018                                         tv = ast_tv(0,0);
2019                                 }
2020                                 if (doidling || pri->resetting) {
2021                                         if (tv.tv_sec > 1) {
2022                                                 tv = ast_tv(1, 0);
2023                                         }
2024                                 } else {
2025                                         if (tv.tv_sec > 60) {
2026                                                 tv = ast_tv(60, 0);
2027                                         }
2028                                 }
2029                         } else if (doidling || pri->resetting) {
2030                                 /* Make sure we stop at least once per second if we're
2031                                    monitoring idle channels */
2032                                 tv = ast_tv(1,0);
2033                         } else {
2034                                 /* Don't poll for more than 60 seconds */
2035                                 tv = ast_tv(60, 0);
2036                         }
2037                         if (!i || ast_tvcmp(tv, lowest) < 0) {
2038                                 lowest = tv;
2039                         }
2040                 }
2041                 ast_mutex_unlock(&pri->lock);
2042
2043                 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
2044                 pthread_testcancel();
2045                 e = NULL;
2046                 res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
2047                 pthread_testcancel();
2048                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
2049
2050                 ast_mutex_lock(&pri->lock);
2051                 if (!res) {
2052                         for (which = 0; which < NUM_DCHANS; which++) {
2053                                 if (!pri->dchans[which])
2054                                         break;
2055                                 /* Just a timeout, run the scheduler */
2056                                 e = pri_schedule_run(pri->dchans[which]);
2057                                 if (e)
2058                                         break;
2059                         }
2060                 } else if (res > -1) {
2061                         for (which = 0; which < NUM_DCHANS; which++) {
2062                                 if (!pri->dchans[which])
2063                                         break;
2064                                 if (fds[which].revents & POLLPRI) {
2065                                         sig_pri_handle_dchan_exception(pri, which);
2066                                 } else if (fds[which].revents & POLLIN) {
2067                                         e = pri_check_event(pri->dchans[which]);
2068                                 }
2069                                 if (e)
2070                                         break;
2071                         }
2072                 } else if (errno != EINTR)
2073                         ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
2074
2075                 if (e) {
2076                         if (pri->debug)
2077                                 pri_dump_event(pri->dchans[which], e);
2078
2079                         if (e->e != PRI_EVENT_DCHAN_DOWN) {
2080                                 if (!(pri->dchanavail[which] & DCHAN_UP)) {
2081                                         ast_verb(2, "%s D-Channel on span %d up\n", pri_order(which), pri->span);
2082                                 }
2083                                 pri->dchanavail[which] |= DCHAN_UP;
2084                         } else {
2085                                 if (pri->dchanavail[which] & DCHAN_UP) {
2086                                         ast_verb(2, "%s D-Channel on span %d down\n", pri_order(which), pri->span);
2087                                 }
2088                                 pri->dchanavail[which] &= ~DCHAN_UP;
2089                         }
2090
2091                         if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
2092                                 /* Must be an NFAS group that has the secondary dchan active */
2093                                 pri->pri = pri->dchans[which];
2094
2095                         switch (e->e) {
2096                         case PRI_EVENT_DCHAN_UP:
2097                                 if (!pri->pri) pri_find_dchan(pri);
2098
2099                                 /* Note presense of D-channel */
2100                                 time(&pri->lastreset);
2101
2102                                 /* Restart in 5 seconds */
2103                                 if (pri->resetinterval > -1) {
2104                                         pri->lastreset -= pri->resetinterval;
2105                                         pri->lastreset += 5;
2106                                 }
2107                                 pri->resetting = 0;
2108                                 /* Take the channels from inalarm condition */
2109                                 for (i = 0; i < pri->numchans; i++)
2110                                         if (pri->pvts[i]) {
2111                                                 pri->pvts[i]->inalarm = 0;
2112                                         }
2113                                 break;
2114                         case PRI_EVENT_DCHAN_DOWN:
2115                                 pri_find_dchan(pri);
2116                                 if (!pri_is_up(pri)) {
2117                                         pri->resetting = 0;
2118                                         if (pri->sig == SIG_BRI_PTMP) {
2119                                                 /* For PTMP connections with non persistent layer 2 we want
2120                                                  * to *not* declare inalarm unless there actually is an alarm */
2121                                                 break;
2122                                         }
2123                                         /* Hangup active channels and put them in alarm mode */
2124                                         for (i = 0; i < pri->numchans; i++) {
2125                                                 struct sig_pri_chan *p = pri->pvts[i];
2126                                                 if (p) {
2127                                                         if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
2128                                                                 /* T309 is not enabled : hangup calls when alarm occurs */
2129                                                                 if (p->call) {
2130                                                                         if (p->pri && p->pri->pri) {
2131                                                                                 pri_hangup(p->pri->pri, p->call, -1);
2132                                                                                 pri_destroycall(p->pri->pri, p->call);
2133                                                                                 p->call = NULL;
2134                                                                         } else
2135                                                                                 ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
2136                                                                 }
2137                                                                 if (p->owner)
2138                                                                         ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
2139                                                         }
2140                                                         p->inalarm = 1;
2141                                                 }
2142                                         }
2143                                 }
2144                                 break;
2145                         case PRI_EVENT_RESTART:
2146                                 if (e->restart.channel > -1) {
2147                                         chanpos = pri_find_principle(pri, e->restart.channel, NULL);
2148                                         if (chanpos < 0)
2149                                                 ast_log(LOG_WARNING, "Restart requested on odd/unavailable channel number %d/%d on span %d\n",
2150                                                         PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
2151                                         else {
2152 #ifdef HAVE_PRI_SERVICE_MESSAGES
2153                                                 char db_chan_name[20], db_answer[5], state;
2154                                                 int why, skipit = 0;
2155
2156                                                 snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->span, pri->pvts[chanpos]->channel);
2157                                                 if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
2158                                                         sscanf(db_answer, "%1c:%30d", &state, &why);
2159                                                         if (why) {
2160                                                                 ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), ignoring RESTART\n", pri->span,
2161                                                                         PRI_CHANNEL(e->restart.channel), (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
2162                                                                 skipit = 1;
2163                                                         } else {
2164                                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
2165                                                         }
2166                                                 }
2167 #endif
2168                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2169 #ifdef HAVE_PRI_SERVICE_MESSAGES
2170                                                 if (!skipit) {
2171 #endif
2172                                                         ast_verb(3, "B-channel %d/%d restarted on span %d\n",
2173                                                                 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
2174                                                         if (pri->pvts[chanpos]->call) {
2175                                                                 pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
2176                                                                 pri->pvts[chanpos]->call = NULL;
2177                                                         }
2178 #ifdef HAVE_PRI_SERVICE_MESSAGES
2179                                                 }
2180 #endif
2181                                                 /* Force soft hangup if appropriate */
2182                                                 if (pri->pvts[chanpos]->owner)
2183                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2184                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2185                                         }
2186                                 } else {
2187                                         ast_verb(3, "Restart requested on entire span %d\n", pri->span);
2188                                         for (x = 0; x < pri->numchans; x++)
2189                                                 if (pri->pvts[x]) {
2190                                                         sig_pri_lock_private(pri->pvts[x]);
2191                                                         if (pri->pvts[x]->call) {
2192                                                                 pri_destroycall(pri->pri, pri->pvts[x]->call);
2193                                                                 pri->pvts[x]->call = NULL;
2194                                                         }
2195                                                         if (pri->pvts[x]->owner)
2196                                                                 ast_softhangup_nolock(pri->pvts[x]->owner, AST_SOFTHANGUP_DEV);
2197                                                         sig_pri_unlock_private(pri->pvts[x]);
2198                                                 }
2199                                 }
2200                                 break;
2201                         case PRI_EVENT_KEYPAD_DIGIT:
2202                                 chanpos = pri_find_principle(pri, e->digit.channel, e->digit.call);
2203                                 if (chanpos < 0) {
2204                                         ast_log(LOG_WARNING, "KEYPAD_DIGITs received on unconfigured channel %d/%d span %d\n",
2205                                                 PRI_SPAN(e->digit.channel), PRI_CHANNEL(e->digit.channel), pri->span);
2206                                 } else {
2207                                         chanpos = pri_fixup_principle(pri, chanpos, e->digit.call);
2208                                         if (chanpos > -1) {
2209                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2210                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->digit.channel,
2211                                                         e->digit.subcmds, e->digit.call);
2212                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
2213                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
2214                                                         && pri->pvts[chanpos]->call == e->digit.call
2215                                                         && pri->pvts[chanpos]->owner) {
2216                                                         /* how to do that */
2217                                                         int digitlen = strlen(e->digit.digits);
2218                                                         int i;
2219
2220                                                         for (i = 0; i < digitlen; i++) {
2221                                                                 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->digit.digits[i], };
2222
2223                                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
2224                                                         }
2225                                                 }
2226                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2227                                         }
2228                                 }
2229                                 break;
2230
2231                         case PRI_EVENT_INFO_RECEIVED:
2232                                 chanpos = pri_find_principle(pri, e->ring.channel, e->ring.call);
2233                                 if (chanpos < 0) {
2234                                         ast_log(LOG_WARNING, "INFO received on unconfigured channel %d/%d span %d\n",
2235                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
2236                                 } else {
2237                                         chanpos = pri_fixup_principle(pri, chanpos, e->ring.call);
2238                                         if (chanpos > -1) {
2239                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2240                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
2241                                                         e->ring.subcmds, e->ring.call);
2242                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
2243                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
2244                                                         && pri->pvts[chanpos]->call == e->ring.call
2245                                                         && pri->pvts[chanpos]->owner) {
2246                                                         /* how to do that */
2247                                                         int digitlen = strlen(e->ring.callednum);
2248                                                         int i;
2249
2250                                                         for (i = 0; i < digitlen; i++) {
2251                                                                 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->ring.callednum[i], };
2252
2253                                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
2254                                                         }
2255                                                 }
2256                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2257                                         }
2258                                 }
2259                                 break;
2260 #ifdef HAVE_PRI_SERVICE_MESSAGES
2261                         case PRI_EVENT_SERVICE:
2262                                 chanpos = pri_find_principle(pri, e->service.channel, NULL);
2263                                 if (chanpos < 0) {
2264                                         ast_log(LOG_WARNING, "Received service change status %d on unconfigured channel %d/%d span %d\n",
2265                                                 e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
2266                                 } else {
2267                                         char db_chan_name[20], db_answer[5], state;
2268                                         int ch, why = -1;
2269
2270                                         ch = pri->pvts[chanpos]->channel;
2271                                         snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->span, ch);
2272                                         if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
2273                                                 sscanf(db_answer, "%1c:%30d", &state, &why);
2274                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
2275                                         }
2276                                         switch (e->service.changestatus) {
2277                                         case 0: /* in-service */
2278                                                 if (why > -1) {
2279                                                         if (why & SRVST_NEAREND) {
2280                                                                 snprintf(db_answer, sizeof(db_answer), "%s:%d", SRVST_TYPE_OOS, SRVST_NEAREND);
2281                                                                 ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
2282                                                                 ast_debug(2, "channel '%d' service state { near: out-of-service,  far: in-service }\n", ch);
2283                                                         }
2284                                                 }
2285                                                 break;
2286                                         case 2: /* out-of-service */
2287                                                 if (why == -1) {
2288                                                         why = SRVST_FAREND;
2289                                                 } else {
2290                                                         why |= SRVST_FAREND;
2291                                                 }
2292                                                 snprintf(db_answer, sizeof(db_answer), "%s:%d", SRVST_TYPE_OOS, why);
2293                                                 ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
2294                                                 break;
2295                                         default:
2296                                                 ast_log(LOG_ERROR, "Huh?  changestatus is: %d\n", e->service.changestatus);
2297                                         }
2298                                         ast_log(LOG_NOTICE, "Channel %d/%d span %d (logical: %d) received a change of service message, status '%d'\n",
2299                                                 PRI_SPAN(e->service.channel), PRI_CHANNEL(e->service.channel), pri->span, ch, e->service.changestatus);
2300                                 }
2301                                 break;
2302                         case PRI_EVENT_SERVICE_ACK:
2303                                 chanpos = pri_find_principle(pri, e->service_ack.channel, NULL);
2304                                 if (chanpos < 0) {
2305                                         ast_log(LOG_WARNING, "Received service acknowledge change status '%d' on unconfigured channel %d/%d span %d\n",
2306                                                 e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
2307                                 } else {
2308                                         ast_debug(2, "Channel %d/%d span %d received a change os service acknowledgement message, status '%d'\n",
2309                                                 PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span, e->service_ack.changestatus);
2310                                 }
2311                                 break;
2312 #endif
2313                         case PRI_EVENT_RING:
2314                                 if (!ast_strlen_zero(pri->msn_list)
2315                                         && !sig_pri_msn_match(pri->msn_list, e->ring.callednum)) {
2316                                         /* The call is not for us so ignore it. */
2317                                         ast_verb(3,
2318                                                 "Ignoring call to '%s' on span %d.  Its not in the MSN list: %s\n",
2319                                                 e->ring.callednum, pri->span, pri->msn_list);
2320                                         pri_destroycall(pri->pri, e->ring.call);
2321                                         break;
2322                                 }
2323                                 if (e->ring.channel == -1)
2324                                         chanpos = pri_find_empty_chan(pri, 1);
2325                                 else
2326                                         chanpos = pri_find_principle(pri, e->ring.channel, e->ring.call);
2327                                 /* if no channel specified find one empty */
2328                                 if (chanpos < 0) {
2329                                         ast_log(LOG_WARNING, "Ring requested on unconfigured channel %d/%d span %d\n",
2330                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
2331                                 } else {
2332                                         sig_pri_lock_private(pri->pvts[chanpos]);
2333                                         if (pri->pvts[chanpos]->owner) {
2334                                                 if (pri->pvts[chanpos]->call == e->ring.call) {
2335                                                         ast_log(LOG_WARNING, "Duplicate setup requested on channel %d/%d already in use on span %d\n",
2336                                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
2337                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
2338                                                         break;
2339                                                 } else {
2340                                                         /* This is where we handle initial glare */
2341                                                         ast_debug(1, "Ring requested on channel %d/%d already in use or previously requested on span %d.  Attempting to renegotiating channel.\n",
2342                                                         PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
2343                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
2344                                                         chanpos = -1;
2345                                                 }
2346                                         }
2347                                         if (chanpos > -1)
2348                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2349                                 }
2350                                 if ((chanpos < 0) && (e->ring.flexible))
2351                                         chanpos = pri_find_empty_chan(pri, 1);
2352                                 if (chanpos > -1) {
2353                                         sig_pri_lock_private(pri->pvts[chanpos]);
2354                                         pri->pvts[chanpos]->call = e->ring.call;
2355
2356                                         /* Use plancallingnum as a scratch buffer since it is initialized next. */
2357                                         apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri,
2358                                                 e->ring.redirectingnum, e->ring.callingplanrdnis);
2359                                         sig_pri_set_rdnis(pri->pvts[chanpos], plancallingnum);
2360
2361                                         /* Setup caller-id info */
2362                                         apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri, e->ring.callingnum, e->ring.callingplan);
2363                                         pri->pvts[chanpos]->cid_ani2 = 0;
2364                                         if (pri->pvts[chanpos]->use_callerid) {
2365                                                 ast_shrink_phone_number(plancallingnum);
2366                                                 ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
2367 #ifdef PRI_ANI
2368                                                 if (!ast_strlen_zero(e->ring.callingani)) {
2369                                                         apply_plan_to_number(plancallingani, sizeof(plancallingani), pri, e->ring.callingani, e->ring.callingplanani);
2370                                                         ast_shrink_phone_number(plancallingani);
2371                                                         ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani, sizeof(pri->pvts[chanpos]->cid_ani));
2372                                                 } else {
2373                                                         pri->pvts[chanpos]->cid_ani[0] = '\0';
2374                                                 }
2375 #endif
2376                                                 pri->pvts[chanpos]->cid_subaddr[0] = '\0';
2377 #if defined(HAVE_PRI_SUBADDR)
2378                                                 if (e->ring.calling.subaddress.valid) {
2379                                                         struct ast_party_subaddress calling_subaddress;
2380
2381                                                         ast_party_subaddress_init(&calling_subaddress);
2382                                                         sig_pri_set_subaddress(&calling_subaddress,
2383                                                                 &e->ring.calling.subaddress);
2384                                                         if (calling_subaddress.str) {
2385                                                                 ast_copy_string(pri->pvts[chanpos]->cid_subaddr,
2386                                                                         calling_subaddress.str,
2387                                                                         sizeof(pri->pvts[chanpos]->cid_subaddr));
2388                                                         }
2389                                                         ast_party_subaddress_free(&calling_subaddress);
2390                                                 }
2391 #endif /* defined(HAVE_PRI_SUBADDR) */
2392                                                 ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
2393                                                 pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
2394                                                 pri->pvts[chanpos]->callingpres = e->ring.callingpres;
2395                                                 if (e->ring.ani2 >= 0) {
2396                                                         pri->pvts[chanpos]->cid_ani2 = e->ring.ani2;
2397                                                 }
2398                                         } else {
2399                                                 pri->pvts[chanpos]->cid_num[0] = '\0';
2400                                                 pri->pvts[chanpos]->cid_subaddr[0] = '\0';
2401                                                 pri->pvts[chanpos]->cid_ani[0] = '\0';
2402                                                 pri->pvts[chanpos]->cid_name[0] = '\0';
2403                                                 pri->pvts[chanpos]->cid_ton = 0;
2404                                                 pri->pvts[chanpos]->callingpres = 0;
2405                                         }
2406                                         sig_pri_set_caller_id(pri->pvts[chanpos]);
2407
2408                                         /* Set DNID on all incoming calls -- even immediate */
2409                                         sig_pri_set_dnid(pri->pvts[chanpos], e->ring.callednum);
2410
2411                                         /* If immediate=yes go to s|1 */
2412                                         if (pri->pvts[chanpos]->immediate) {
2413                                                 ast_verb(3, "Going to extension s|1 because of immediate=yes\n");
2414                                                 pri->pvts[chanpos]->exten[0] = 's';
2415                                                 pri->pvts[chanpos]->exten[1] = '\0';
2416                                         }
2417                                         /* Get called number */
2418                                         else if (!ast_strlen_zero(e->ring.callednum)) {
2419                                                 ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
2420                                         } else if (pri->overlapdial)
2421                                                 pri->pvts[chanpos]->exten[0] = '\0';
2422                                         else {
2423                                                 /* Some PRI circuits are set up to send _no_ digits.  Handle them as 's'. */
2424                                                 pri->pvts[chanpos]->exten[0] = 's';
2425                                                 pri->pvts[chanpos]->exten[1] = '\0';
2426                                         }
2427                                         /* No number yet, but received "sending complete"? */
2428                                         if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
2429                                                 ast_verb(3, "Going to extension s|1 because of Complete received\n");
2430                                                 pri->pvts[chanpos]->exten[0] = 's';
2431                                                 pri->pvts[chanpos]->exten[1] = '\0';
2432                                         }
2433
2434                                         /* Make sure extension exists (or in overlap dial mode, can exist) */
2435                                         if (((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
2436                                                 ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
2437                                                 /* Setup law */
2438                                                 if (e->ring.complete || !(pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
2439                                                         /* Just announce proceeding */
2440                                                         pri->pvts[chanpos]->proceeding = 1;
2441                                                         pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
2442                                                 } else {
2443                                                         if (pri->switchtype != PRI_SWITCH_GR303_TMC)
2444                                                                 pri_need_more_info(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
2445                                                         else
2446                                                                 pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
2447                                                 }
2448
2449                                                 /* Start PBX */
2450                                                 if (!e->ring.complete
2451                                                         && (pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
2452                                                         && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
2453                                                         /*
2454                                                          * Release the PRI lock while we create the channel
2455                                                          * so other threads can send D channel messages.
2456                                                          */
2457                                                         ast_mutex_unlock(&pri->lock);
2458                                                         c = sig_pri_new_ast_channel(pri->pvts[chanpos],
2459                                                                 AST_STATE_RESERVED, 0,
2460                                                                 (e->ring.layer1 == PRI_LAYER_1_ALAW)
2461                                                                         ? SIG_PRI_ALAW : SIG_PRI_ULAW,
2462                                                                 e->ring.ctype, pri->pvts[chanpos]->exten, NULL);
2463                                                         ast_mutex_lock(&pri->lock);
2464                                                         if (c) {
2465 #if defined(HAVE_PRI_SUBADDR)
2466                                                                 if (e->ring.calling.subaddress.valid) {
2467                                                                         /* Set Calling Subaddress */
2468                                                                         sig_pri_lock_owner(pri, chanpos);
2469                                                                         sig_pri_set_subaddress(
2470                                                                                 &pri->pvts[chanpos]->owner->cid.subaddress,
2471                                                                                 &e->ring.calling.subaddress);
2472                                                                         if (!e->ring.calling.subaddress.type
2473                                                                                 && !ast_strlen_zero(
2474                                                                                         (char *) e->ring.calling.subaddress.data)) {
2475                                                                                 /* NSAP */
2476                                                                                 pbx_builtin_setvar_helper(c, "CALLINGSUBADDR",
2477                                                                                         (char *) e->ring.calling.subaddress.data);
2478                                                                         }
2479                                                                         ast_channel_unlock(c);
2480                                                                 }
2481                                                                 if (e->ring.called_subaddress.valid) {
2482                                                                         /* Set Called Subaddress */
2483                                                                         sig_pri_lock_owner(pri, chanpos);
2484                                                                         sig_pri_set_subaddress(
2485                                                                                 &pri->pvts[chanpos]->owner->cid.dialed_subaddress,
2486                                                                                 &e->ring.called_subaddress);
2487                                                                         if (!e->ring.called_subaddress.type
2488                                                                                 && !ast_strlen_zero(
2489                                                                                         (char *) e->ring.called_subaddress.data)) {
2490                                                                                 /* NSAP */
2491                                                                                 pbx_builtin_setvar_helper(c, "CALLEDSUBADDR",
2492                                                                                         (char *) e->ring.called_subaddress.data);
2493                                                                         }
2494                                                                         ast_channel_unlock(c);
2495                                                                 }
2496 #else
2497                                                                 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
2498                                                                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
2499                                                                 }
2500 #endif /* !defined(HAVE_PRI_SUBADDR) */
2501                                                                 if (e->ring.ani2 >= 0) {
2502                                                                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
2503                                                                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
2504                                                                 }
2505
2506 #ifdef SUPPORT_USERUSER
2507                                                                 if (!ast_strlen_zero(e->ring.useruserinfo)) {
2508                                                                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
2509                                                                 }
2510 #endif
2511
2512                                                                 snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
2513                                                                 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
2514                                                                 if (e->ring.redirectingreason >= 0) {
2515                                                                         /* This is now just a status variable.  Use REDIRECTING() dialplan function. */
2516                                                                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
2517                                                                 }
2518 #if defined(HAVE_PRI_REVERSE_CHARGE)
2519                                                                 pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
2520 #endif
2521 #if defined(HAVE_PRI_SETUP_KEYPAD)
2522                                                                 ast_copy_string(pri->pvts[chanpos]->keypad_digits,
2523                                                                         e->ring.keypad_digits,
2524                                                                         sizeof(pri->pvts[chanpos]->keypad_digits));
2525 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
2526
2527                                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
2528                                                                         e->ring.subcmds, e->ring.call);
2529
2530                                                         }
2531                                                         if (c && !ast_pthread_create_detached(&threadid, NULL, pri_ss_thread, pri->pvts[chanpos])) {
2532                                                                 ast_verb(3, "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
2533                                                                         plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
2534                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
2535                                                         } else {
2536                                                                 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
2537                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
2538                                                                 if (c)
2539                                                                         ast_hangup(c);
2540                                                                 else {
2541                                                                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
2542                                                                         pri->pvts[chanpos]->call = NULL;
2543                                                                 }
2544                                                         }
2545                                                 } else {
2546                                                         /*
2547                                                          * Release the PRI lock while we create the channel
2548                                                          * so other threads can send D channel messages.
2549                                                          */
2550                                                         ast_mutex_unlock(&pri->lock);
2551                                                         c = sig_pri_new_ast_channel(pri->pvts[chanpos],
2552                                                                 AST_STATE_RING, 0,
2553                                                                 (e->ring.layer1 == PRI_LAYER_1_ALAW)
2554                                                                         ? SIG_PRI_ALAW : SIG_PRI_ULAW, e->ring.ctype,
2555                                                                 pri->pvts[chanpos]->exten, NULL);
2556                                                         ast_mutex_lock(&pri->lock);
2557                                                         if (c) {
2558                                                                 /*
2559                                                                  * It is reasonably safe to set the following
2560                                                                  * channel variables while the PRI and DAHDI private
2561                                                                  * structures are locked.  The PBX has not been
2562                                                                  * started yet and it is unlikely that any other task
2563                                                                  * will do anything with the channel we have just
2564                                                                  * created.
2565                                                                  */
2566 #if defined(HAVE_PRI_SUBADDR)
2567                                                                 if (e->ring.calling.subaddress.valid) {
2568                                                                         /* Set Calling Subaddress */
2569                                                                         sig_pri_lock_owner(pri, chanpos);
2570                                                                         sig_pri_set_subaddress(
2571                                                                                 &pri->pvts[chanpos]->owner->cid.subaddress,
2572                                                                                 &e->ring.calling.subaddress);
2573                                                                         if (!e->ring.calling.subaddress.type
2574                                                                                 && !ast_strlen_zero(
2575                                                                                         (char *) e->ring.calling.subaddress.data)) {
2576                                                                                 /* NSAP */
2577                                                                                 pbx_builtin_setvar_helper(c, "CALLINGSUBADDR",
2578                                                                                         (char *) e->ring.calling.subaddress.data);
2579                                                                         }
2580                                                                         ast_channel_unlock(c);
2581                                                                 }
2582                                                                 if (e->ring.called_subaddress.valid) {
2583                                                                         /* Set Called Subaddress */
2584                                                                         sig_pri_lock_owner(pri, chanpos);
2585                                                                         sig_pri_set_subaddress(
2586                                                                                 &pri->pvts[chanpos]->owner->cid.dialed_subaddress,
2587                                                                                 &e->ring.called_subaddress);
2588                                                                         if (!e->ring.called_subaddress.type
2589                                                                                 && !ast_strlen_zero(
2590                                                                                         (char *) e->ring.called_subaddress.data)) {
2591                                                                                 /* NSAP */
2592                                                                                 pbx_builtin_setvar_helper(c, "CALLEDSUBADDR",
2593                                                                                         (char *) e->ring.called_subaddress.data);
2594                                                                         }
2595                                                                         ast_channel_unlock(c);
2596                                                                 }
2597 #else
2598                                                                 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
2599                                                                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
2600                                                                 }
2601 #endif /* !defined(HAVE_PRI_SUBADDR) */
2602                                                                 if (e->ring.ani2 >= 0) {
2603                                                                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
2604                                                                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
2605                                                                 }
2606
2607 #ifdef SUPPORT_USERUSER
2608                                                                 if (!ast_strlen_zero(e->ring.useruserinfo)) {
2609                                                                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
2610                                                                 }
2611 #endif
2612
2613                                                                 if (e->ring.redirectingreason >= 0) {
2614                                                                         /* This is now just a status variable.  Use REDIRECTING() dialplan function. */
2615                                                                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
2616                                                                 }
2617 #if defined(HAVE_PRI_REVERSE_CHARGE)
2618                                                                 pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
2619 #endif
2620 #if defined(HAVE_PRI_SETUP_KEYPAD)
2621                                                                 ast_copy_string(pri->pvts[chanpos]->keypad_digits,
2622                                                                         e->ring.keypad_digits,
2623                                                                         sizeof(pri->pvts[chanpos]->keypad_digits));
2624 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
2625
2626                                                                 snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
2627                                                                 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
2628
2629                                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
2630                                                                         e->ring.subcmds, e->ring.call);
2631
2632                                                         }
2633                                                         if (c && !ast_pbx_start(c)) {
2634                                                                 ast_verb(3, "Accepting call from '%s' to '%s' on channel %d/%d, span %d\n",
2635                                                                         plancallingnum, pri->pvts[chanpos]->exten,
2636                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
2637                                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
2638                                                         } else {
2639                                                                 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
2640                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
2641                                                                 if (c) {
2642                                                                         ast_hangup(c);
2643                                                                 } else {
2644                                                                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
2645                                                                         pri->pvts[chanpos]->call = NULL;
2646                                                                 }
2647                                                         }
2648                                                 }
2649                                         } else {
2650                                                 ast_verb(3, "Extension '%s' in context '%s' from '%s' does not exist.  Rejecting call on channel %d/%d, span %d\n",
2651                                                         pri->pvts[chanpos]->exten, pri->pvts[chanpos]->context, pri->pvts[chanpos]->cid_num, pri->pvts[chanpos]->logicalspan,
2652                                                         pri->pvts[chanpos]->prioffset, pri->span);
2653                                                 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_UNALLOCATED);
2654                                                 pri->pvts[chanpos]->call = NULL;
2655                                                 pri->pvts[chanpos]->exten[0] = '\0';
2656                                         }
2657                                         sig_pri_unlock_private(pri->pvts[chanpos]);
2658                                 } else {
2659                                         if (e->ring.flexible)
2660                                                 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
2661                                         else
2662                                                 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
2663                                 }
2664                                 break;
2665                         case PRI_EVENT_RINGING:
2666                                 chanpos = pri_find_principle(pri, e->ringing.channel, e->ringing.call);
2667                                 if (chanpos < 0) {
2668                                         ast_log(LOG_WARNING, "Ringing requested on unconfigured channel %d/%d span %d\n",
2669                                                 PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
2670                                 } else {
2671                                         chanpos = pri_fixup_principle(pri, chanpos, e->ringing.call);
2672                                         if (chanpos < 0) {
2673                                                 ast_log(LOG_WARNING, "Ringing requested on channel %d/%d not in use on span %d\n",
2674                                                         PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
2675                                         } else {
2676                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2677
2678                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ringing.channel,
2679                                                         e->ringing.subcmds, e->ringing.call);
2680                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
2681                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_RINGING, pri);
2682                                                 pri->pvts[chanpos]->alerting = 1;
2683
2684 #ifdef SUPPORT_USERUSER
2685                                                 if (!ast_strlen_zero(e->ringing.useruserinfo)) {
2686                                                         struct ast_channel *owner;
2687
2688                                                         sig_pri_lock_owner(pri, chanpos);
2689                                                         owner = pri->pvts[chanpos]->owner;
2690                                                         if (owner) {
2691                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
2692                                                                         e->ringing.useruserinfo);
2693                                                                 ast_channel_unlock(owner);
2694                                                         }
2695                                                 }
2696 #endif
2697
2698                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2699                                         }
2700                                 }
2701                                 break;
2702                         case PRI_EVENT_PROGRESS:
2703                                 /* Get chan value if e->e is not PRI_EVNT_RINGING */
2704                                 chanpos = pri_find_principle(pri, e->proceeding.channel, e->proceeding.call);
2705                                 if (chanpos > -1) {
2706                                         sig_pri_lock_private(pri->pvts[chanpos]);
2707                                         sig_pri_handle_subcmds(pri, chanpos, e->e, e->proceeding.channel,
2708                                                 e->proceeding.subcmds, e->proceeding.call);
2709                                         if ((!pri->pvts[chanpos]->progress)
2710 #ifdef PRI_PROGRESS_MASK
2711                                                 || (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE)
2712 #else
2713                                                 || (e->proceeding.progress == 8)
2714 #endif
2715                                                 ) {
2716                                                 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_PROGRESS, };
2717
2718                                                 if (e->proceeding.cause > -1) {
2719                                                         ast_verb(3, "PROGRESS with cause code %d received\n", e->proceeding.cause);
2720
2721                                                         /* Work around broken, out of spec USER_BUSY cause in a progress message */
2722                                                         if (e->proceeding.cause == AST_CAUSE_USER_BUSY) {
2723                                                                 if (pri->pvts[chanpos]->owner) {
2724                                                                         ast_verb(3, "PROGRESS with 'user busy' received, signaling AST_CONTROL_BUSY instead of AST_CONTROL_PROGRESS\n");
2725
2726                                                                         pri->pvts[chanpos]->owner->hangupcause = e->proceeding.cause;
2727                                                                         f.subclass.integer = AST_CONTROL_BUSY;
2728                                                                 }
2729                                                         }
2730                                                 }
2731
2732                                                 ast_debug(1, "Queuing frame from PRI_EVENT_PROGRESS on channel %d/%d span %d\n",
2733                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
2734                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
2735                                                 if (
2736 #ifdef PRI_PROGRESS_MASK
2737                                                         e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE
2738 #else
2739                                                         e->proceeding.progress == 8
2740 #endif
2741                                                         ) {
2742                                                         /* Bring voice path up */
2743                                                         f.subclass.integer = AST_CONTROL_PROGRESS;
2744                                                         pri_queue_frame(pri->pvts[chanpos], &f, pri);
2745                                                 }
2746                                                 pri->pvts[chanpos]->progress = 1;
2747                                                 sig_pri_set_dialing(pri->pvts[chanpos], 0);
2748                                         }
2749                                         sig_pri_unlock_private(pri->pvts[chanpos]);
2750                                 }
2751                                 break;
2752                         case PRI_EVENT_PROCEEDING:
2753                                 chanpos = pri_find_principle(pri, e->proceeding.channel, e->proceeding.call);
2754                                 if (chanpos > -1) {
2755                                         sig_pri_lock_private(pri->pvts[chanpos]);
2756                                         sig_pri_handle_subcmds(pri, chanpos, e->e, e->proceeding.channel,
2757                                                 e->proceeding.subcmds, e->proceeding.call);
2758                                         if (!pri->pvts[chanpos]->proceeding) {
2759                                                 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_PROCEEDING, };
2760
2761                                                 ast_debug(1, "Queuing frame from PRI_EVENT_PROCEEDING on channel %d/%d span %d\n",
2762                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
2763                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
2764                                                 if (
2765 #ifdef PRI_PROGRESS_MASK
2766                                                         e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE
2767 #else
2768                                                         e->proceeding.progress == 8
2769 #endif
2770                                                         ) {
2771                                                         /* Bring voice path up */
2772                                                         f.subclass.integer = AST_CONTROL_PROGRESS;
2773                                                         pri_queue_frame(pri->pvts[chanpos], &f, pri);
2774                                                 }
2775                                                 pri->pvts[chanpos]->proceeding = 1;
2776                                                 sig_pri_set_dialing(pri->pvts[chanpos], 0);
2777                                         }
2778                                         sig_pri_unlock_private(pri->pvts[chanpos]);
2779                                 }
2780                                 break;
2781                         case PRI_EVENT_FACILITY:
2782                                 chanpos = pri_find_principle(pri, e->facility.channel, e->facility.call);
2783                                 if (chanpos < 0) {
2784                                         ast_log(LOG_WARNING, "Facility requested on unconfigured channel %d/%d span %d\n",
2785                                                 PRI_SPAN(e->facility.channel), PRI_CHANNEL(e->facility.channel), pri->span);
2786                                 } else {
2787                                         chanpos = pri_fixup_principle(pri, chanpos, e->facility.call);
2788                                         if (chanpos < 0) {
2789                                                 ast_log(LOG_WARNING, "Facility requested on channel %d/%d not in use on span %d\n",
2790                                                         PRI_SPAN(e->facility.channel), PRI_CHANNEL(e->facility.channel), pri->span);
2791                                         } else {
2792                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2793 #if defined(HAVE_PRI_CALL_REROUTING)
2794                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->facility.channel,
2795                                                         e->facility.subcmds, e->facility.subcall);
2796 #else
2797                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->facility.channel,
2798                                                         e->facility.subcmds, e->facility.call);
2799 #endif  /* !defined(HAVE_PRI_CALL_REROUTING) */
2800                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2801                                         }
2802                                 }
2803                                 break;
2804                         case PRI_EVENT_ANSWER:
2805                                 chanpos = pri_find_principle(pri, e->answer.channel, e->answer.call);
2806                                 if (chanpos < 0) {
2807                                         ast_log(LOG_WARNING, "Answer on unconfigured channel %d/%d span %d\n",
2808                                                 PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
2809                                 } else {
2810                                         chanpos = pri_fixup_principle(pri, chanpos, e->answer.call);
2811                                         if (chanpos < 0) {
2812                                                 ast_log(LOG_WARNING, "Answer requested on channel %d/%d not in use on span %d\n",
2813                                                         PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
2814                                         } else {
2815                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2816
2817                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->answer.channel,
2818                                                         e->answer.subcmds, e->answer.call);
2819                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_ANSWER, pri);
2820                                                 /* Enable echo cancellation if it's not on already */
2821                                                 sig_pri_set_dialing(pri->pvts[chanpos], 0);
2822                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
2823
2824 #ifdef SUPPORT_USERUSER
2825                                                 if (!ast_strlen_zero(e->answer.useruserinfo)) {
2826                                                         struct ast_channel *owner;
2827
2828                                                         sig_pri_lock_owner(pri, chanpos);
2829                                                         owner = pri->pvts[chanpos]->owner;
2830                                                         if (owner) {
2831                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
2832                                                                         e->answer.useruserinfo);
2833                                                                 ast_channel_unlock(owner);
2834                                                         }
2835                                                 }
2836 #endif
2837
2838                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2839                                         }
2840                                 }
2841                                 break;
2842                         case PRI_EVENT_HANGUP:
2843                                 chanpos = pri_find_principle(pri, e->hangup.channel, e->hangup.call);
2844                                 if (chanpos < 0) {
2845                                         ast_log(LOG_WARNING, "Hangup requested on unconfigured channel %d/%d span %d\n",
2846                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2847                                 } else {
2848                                         chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
2849                                         if (chanpos > -1) {
2850                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2851                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->hangup.channel,
2852                                                         e->hangup.subcmds, e->hangup.call);
2853                                                 if (!pri->pvts[chanpos]->alreadyhungup) {
2854                                                         /* we're calling here dahdi_hangup so once we get there we need to clear p->call after calling pri_hangup */
2855                                                         pri->pvts[chanpos]->alreadyhungup = 1;
2856                                                         if (pri->pvts[chanpos]->owner) {
2857                                                                 /* Queue a BUSY instead of a hangup if our cause is appropriate */
2858                                                                 pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
2859                                                                 switch (pri->pvts[chanpos]->owner->_state) {
2860                                                                 case AST_STATE_BUSY:
2861                                                                 case AST_STATE_UP:
2862                                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2863                                                                         break;
2864                                                                 default:
2865                                                                         switch (e->hangup.cause) {
2866                                                                         case PRI_CAUSE_USER_BUSY:
2867                                                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_BUSY, pri);
2868                                                                                 break;
2869                                                                         case PRI_CAUSE_CALL_REJECTED:
2870                                                                         case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
2871                                                                         case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
2872                                                                         case PRI_CAUSE_SWITCH_CONGESTION:
2873                                                                         case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
2874                                                                         case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
2875                                                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_CONGESTION, pri);
2876                                                                                 break;
2877                                                                         default:
2878                                                                                 ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2879                                                                                 break;
2880                                                                         }
2881                                                                         break;
2882                                                                 }
2883                                                         }
2884                                                         ast_verb(3, "Channel %d/%d, span %d got hangup, cause %d\n",
2885                                                                 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, e->hangup.cause);
2886                                                 } else {
2887                                                         pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
2888                                                         pri->pvts[chanpos]->call = NULL;
2889                                                 }
2890                                                 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
2891                                                         ast_verb(3, "Forcing restart of channel %d/%d on span %d since channel reported in use\n",
2892                                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2893                                                         pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
2894                                                         pri->pvts[chanpos]->resetting = 1;
2895                                                 }
2896                                                 if (e->hangup.aoc_units > -1)
2897                                                         ast_verb(3, "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
2898                                                                 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
2899
2900 #ifdef SUPPORT_USERUSER
2901                                                 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
2902                                                         struct ast_channel *owner;
2903
2904                                                         sig_pri_lock_owner(pri, chanpos);
2905                                                         owner = pri->pvts[chanpos]->owner;
2906                                                         if (owner) {
2907                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
2908                                                                         e->hangup.useruserinfo);
2909                                                                 ast_channel_unlock(owner);
2910                                                         }
2911                                                 }
2912 #endif
2913
2914                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2915                                         } else {
2916                                                 ast_log(LOG_WARNING, "Hangup on bad channel %d/%d on span %d\n",
2917                                                         PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2918                                         }
2919                                 }
2920                                 break;
2921                         case PRI_EVENT_HANGUP_REQ:
2922                                 chanpos = pri_find_principle(pri, e->hangup.channel, e->hangup.call);
2923                                 if (chanpos < 0) {
2924                                         ast_log(LOG_WARNING, "Hangup REQ requested on unconfigured channel %d/%d span %d\n",
2925                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2926                                 } else {
2927                                         chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
2928                                         if (chanpos > -1) {
2929                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2930                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->hangup.channel,
2931                                                         e->hangup.subcmds, e->hangup.call);
2932 #if defined(HAVE_PRI_CALL_HOLD)
2933                                                 if (e->hangup.call_active && e->hangup.call_held
2934                                                         && pri->hold_disconnect_transfer) {
2935                                                         /* We are to transfer the call instead of simply hanging up. */
2936                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
2937                                                         if (!sig_pri_attempt_transfer(pri, e->hangup.call_active,
2938                                                                 e->hangup.call_held)) {
2939                                                                 break;
2940                                                         }
2941                                                         sig_pri_lock_private(pri->pvts[chanpos]);
2942                                                 }
2943 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
2944                                                 if (pri->pvts[chanpos]->owner) {
2945                                                         pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
2946                                                         switch (pri->pvts[chanpos]->owner->_state) {
2947                                                         case AST_STATE_BUSY:
2948                                                         case AST_STATE_UP:
2949                                                                 ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2950                                                                 break;
2951                                                         default:
2952                                                                 switch (e->hangup.cause) {
2953                                                                 case PRI_CAUSE_USER_BUSY:
2954                                                                         pri_queue_control(pri->pvts[chanpos], AST_CONTROL_BUSY, pri);
2955                                                                         break;
2956                                                                 case PRI_CAUSE_CALL_REJECTED:
2957                                                                 case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
2958                                                                 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
2959                                                                 case PRI_CAUSE_SWITCH_CONGESTION:
2960                                                                 case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
2961                                                                 case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
2962                                                         &n