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