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