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