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