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