9276ebb155a4a3742950c54fb70a00b5573a2ef0
[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, struct sig_pri_chan *new)
528 {
529         if (old->calls->fixup_chans)
530                 old->calls->fixup_chans(old->chan_pvt, new->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         f.subclass = subclass;
659         pri_queue_frame(p, &f, pri);
660 }
661
662 static int pri_find_principle(struct sig_pri_pri *pri, int channel)
663 {
664         int x;
665         int span = PRI_SPAN(channel);
666         int principle = -1;
667         int explicit = PRI_EXPLICIT(channel);
668         channel = PRI_CHANNEL(channel);
669
670         if (!explicit) {
671                 int index = pri_active_dchan_index(pri);
672                 if (index == -1)
673                         return -1;
674                 span = pri->dchan_logical_span[index];
675         }
676
677         for (x = 0; x < pri->numchans; x++) {
678                 if (pri->pvts[x] && (pri->pvts[x]->prioffset == channel) && (pri->pvts[x]->logicalspan == span)) {
679                         principle = x;
680                         break;
681                 }
682         }
683
684         return principle;
685 }
686
687 static int pri_fixup_principle(struct sig_pri_pri *pri, int principle, q931_call *c)
688 {
689         int x;
690         if (!c) {
691                 if (principle < 0)
692                         return -1;
693                 return principle;
694         }
695         if ((principle > -1) &&
696                 (principle < pri->numchans) &&
697                 (pri->pvts[principle]) &&
698                 (pri->pvts[principle]->call == c))
699                 return principle;
700         /* First, check for other bearers */
701         for (x = 0; x < pri->numchans; x++) {
702                 if (!pri->pvts[x])
703                         continue;
704                 if (pri->pvts[x]->call == c) {
705                         /* Found our call */
706                         if (principle != x) {
707                                 struct sig_pri_chan *new = pri->pvts[principle], *old = pri->pvts[x];
708
709                                 ast_verb(3, "Moving call from channel %d to channel %d\n",
710                                         old->channel, new->channel);
711                                 if (new->owner) {
712                                         ast_log(LOG_WARNING, "Can't fix up channel from %d to %d because %d is already in use\n",
713                                                 old->channel, new->channel, new->channel);
714                                         return -1;
715                                 }
716
717                                 sig_pri_fixup_chans(old, new);
718                                 /* Fix it all up now */
719                                 new->owner = old->owner;
720                                 old->owner = NULL;
721
722                                 new->call = old->call;
723                                 old->call = NULL;
724
725                         }
726                         return principle;
727                 }
728         }
729         ast_log(LOG_WARNING, "Call specified, but not found?\n");
730         return -1;
731 }
732
733 static char * redirectingreason2str(int redirectingreason)
734 {
735         switch (redirectingreason) {
736         case 0:
737                 return "UNKNOWN";
738         case 1:
739                 return "BUSY";
740         case 2:
741                 return "NO_REPLY";
742         case 0xF:
743                 return "UNCONDITIONAL";
744         default:
745                 return "NOREDIRECT";
746         }
747 }
748
749 static char *dialplan2str(int dialplan)
750 {
751         if (dialplan == -1) {
752                 return("Dynamically set dialplan in ISDN");
753         }
754         return (pri_plan2str(dialplan));
755 }
756
757 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_pri *pri, const char *number, const int plan)
758 {
759         switch (plan) {
760         case PRI_INTERNATIONAL_ISDN:            /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
761                 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
762                 break;
763         case PRI_NATIONAL_ISDN:                 /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
764                 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
765                 break;
766         case PRI_LOCAL_ISDN:                    /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
767                 snprintf(buf, size, "%s%s", pri->localprefix, number);
768                 break;
769         case PRI_PRIVATE:                       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
770                 snprintf(buf, size, "%s%s", pri->privateprefix, number);
771                 break;
772         case PRI_UNKNOWN:                       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
773                 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
774                 break;
775         default:                                /* other Q.931 dialplan => don't twiddle with callingnum */
776                 snprintf(buf, size, "%s", number);
777                 break;
778         }
779 }
780
781 static int pri_check_restart(struct sig_pri_pri *pri)
782 {
783 #ifdef HAVE_PRI_SERVICE_MESSAGES
784 tryanotherpos:
785 #endif
786         do {
787                 pri->resetpos++;
788         } while ((pri->resetpos < pri->numchans) &&
789                 (!pri->pvts[pri->resetpos] ||
790                 pri->pvts[pri->resetpos]->call ||
791                 pri->pvts[pri->resetpos]->resetting));
792         if (pri->resetpos < pri->numchans) {
793 #ifdef HAVE_PRI_SERVICE_MESSAGES
794                 char db_chan_name[20], db_answer[5], state;
795                 int why;
796
797                 /* check if the channel is out of service */
798                 ast_mutex_lock(&pri->pvts[pri->resetpos]->service_lock);
799                 snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->pvts[pri->resetpos]->pri->span, pri->pvts[pri->resetpos]->channel);
800                 ast_mutex_unlock(&pri->pvts[pri->resetpos]->service_lock);
801
802                 /* if so, try next channel */
803                 if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
804                         sscanf(db_answer, "%1c:%30d", &state, &why);
805                         if (why) {
806                                 ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), not sending RESTART\n", pri->span,
807                                 pri->pvts[pri->resetpos]->channel, (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
808                                 goto tryanotherpos;
809                         }
810                 }
811 #endif
812
813                 /* Mark the channel as resetting and restart it */
814                 pri->pvts[pri->resetpos]->resetting = 1;
815                 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
816         } else {
817                 pri->resetting = 0;
818                 time(&pri->lastreset);
819         }
820         return 0;
821 }
822
823 static int pri_find_empty_chan(struct sig_pri_pri *pri, int backwards)
824 {
825         int x;
826         if (backwards)
827                 x = pri->numchans;
828         else
829                 x = 0;
830         for (;;) {
831                 if (backwards && (x < 0))
832                         break;
833                 if (!backwards && (x >= pri->numchans))
834                         break;
835                 if (pri->pvts[x] && !pri->pvts[x]->inalarm && !pri->pvts[x]->owner) {
836                         ast_debug(1, "Found empty available channel %d/%d\n",
837                                 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
838                         return x;
839                 }
840                 if (backwards)
841                         x--;
842                 else
843                         x++;
844         }
845         return -1;
846 }
847
848 static void *do_idle_thread(void *vchan)
849 {
850         struct ast_channel *chan = vchan;
851         struct sig_pri_chan *pvt = chan->tech_pvt;
852         struct ast_frame *f;
853         char ex[80];
854         /* Wait up to 30 seconds for an answer */
855         int newms, ms = 30000;
856         ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
857         snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
858         if (ast_call(chan, ex, 0)) {
859                 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
860                 ast_hangup(chan);
861                 return NULL;
862         }
863         while ((newms = ast_waitfor(chan, ms)) > 0) {
864                 f = ast_read(chan);
865                 if (!f) {
866                         /* Got hangup */
867                         break;
868                 }
869                 if (f->frametype == AST_FRAME_CONTROL) {
870                         switch (f->subclass) {
871                         case AST_CONTROL_ANSWER:
872                                 /* Launch the PBX */
873                                 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
874                                 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
875                                 chan->priority = 1;
876                                 ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
877                                 ast_pbx_run(chan);
878                                 /* It's already hungup, return immediately */
879                                 return NULL;
880                         case AST_CONTROL_BUSY:
881                                 ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
882                                 break;
883                         case AST_CONTROL_CONGESTION:
884                                 ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
885                                 break;
886                         };
887                 }
888                 ast_frfree(f);
889                 ms = newms;
890         }
891         /* Hangup the channel since nothing happend */
892         ast_hangup(chan);
893         return NULL;
894 }
895
896 static void *pri_ss_thread(void *data)
897 {
898         struct sig_pri_chan *p = data;
899         struct ast_channel *chan = p->owner;
900         char exten[AST_MAX_EXTENSION];
901         int res;
902         int len;
903         int timeout;
904
905         if (!chan) {
906                 /* We lost the owner before we could get started. */
907                 return NULL;
908         }
909
910         /*
911          * In the bizarre case where the channel has become a zombie before we
912          * even get started here, abort safely.
913          */
914         if (!chan->tech_pvt) {
915                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
916                 ast_hangup(chan);
917                 return NULL;
918         }
919
920         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
921
922         sig_pri_dsp_reset_and_flush_digits(p);
923
924         /* Now loop looking for an extension */
925         ast_copy_string(exten, p->exten, sizeof(exten));
926         len = strlen(exten);
927         res = 0;
928         while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
929                 if (len && !ast_ignore_pattern(chan->context, exten))
930                         sig_pri_play_tone(p, -1);
931                 else
932                         sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
933                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
934                         timeout = pri_matchdigittimeout;
935                 else
936                         timeout = pri_gendigittimeout;
937                 res = ast_waitfordigit(chan, timeout);
938                 if (res < 0) {
939                         ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
940                         ast_hangup(chan);
941                         return NULL;
942                 } else if (res) {
943                         exten[len++] = res;
944                         exten[len] = '\0';
945                 } else
946                         goto exit;
947         }
948         /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
949         if (ast_strlen_zero(exten)) {
950                 ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
951                 exten[0] = 's';
952                 exten[1] = '\0';
953         } else {
954                 if (chan->cid.cid_dnid) {
955                         ast_free(chan->cid.cid_dnid);
956                 }
957                 chan->cid.cid_dnid = ast_strdup(exten);
958         }
959         sig_pri_play_tone(p, -1);
960         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
961                 /* Start the real PBX */
962                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
963                 sig_pri_dsp_reset_and_flush_digits(p);
964                 sig_pri_set_echocanceller(p, 1);
965                 ast_setstate(chan, AST_STATE_RING);
966                 res = ast_pbx_run(chan);
967                 if (res) {
968                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
969                 }
970         } else {
971                 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
972                 chan->hangupcause = AST_CAUSE_UNALLOCATED;
973                 ast_hangup(chan);
974                 p->exten[0] = '\0';
975                 /* Since we send release complete here, we won't get one */
976                 p->call = NULL;
977         }
978         return NULL;
979
980 exit:
981         res = sig_pri_play_tone(p, SIG_PRI_TONE_CONGESTION);
982         if (res < 0)
983                 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
984         ast_hangup(chan);
985         return NULL;
986 }
987
988 void pri_event_alarm(struct sig_pri_pri *pri, int index, int before_start_pri)
989 {
990         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
991         if (!before_start_pri)
992                 pri_find_dchan(pri);
993 }
994
995 void pri_event_noalarm(struct sig_pri_pri *pri, int index, int before_start_pri)
996 {
997         pri->dchanavail[index] |= DCHAN_NOTINALARM;
998         if (!before_start_pri)
999                 pri_restart(pri->dchans[index]);
1000 }
1001
1002 /*!
1003  * \internal
1004  * \brief Obtain the sig_pri owner channel lock if the owner exists.
1005  * \since 1.6.3
1006  *
1007  * \param pri sig_pri PRI control structure.
1008  * \param chanpos Channel position in the span.
1009  *
1010  * \note Assumes the pri->lock is already obtained.
1011  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1012  *
1013  * \return Nothing
1014  */
1015 static void sig_pri_lock_owner(struct sig_pri_pri *pri, int chanpos)
1016 {
1017         for (;;) {
1018                 if (!pri->pvts[chanpos]->owner) {
1019                         /* There is no owner lock to get. */
1020                         break;
1021                 }
1022                 if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
1023                         /* We got the lock */
1024                         break;
1025                 }
1026                 /* We must unlock the PRI to avoid the possibility of a deadlock */
1027                 ast_mutex_unlock(&pri->lock);
1028                 PRI_DEADLOCK_AVOIDANCE(pri->pvts[chanpos]);
1029                 ast_mutex_lock(&pri->lock);
1030         }
1031 }
1032
1033 /*!
1034  * \internal
1035  * \brief Handle the call associated PRI subcommand events.
1036  * \since 1.6.3
1037  *
1038  * \param pri sig_pri PRI control structure.
1039  * \param chanpos Channel position in the span.
1040  * \param event_id PRI event id
1041  * \param channel PRI encoded span/channel
1042  * \param subcmds Subcommands to process if any. (Could be NULL).
1043  *
1044  * \note Assumes the pri->lock is already obtained.
1045  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1046  *
1047  * \return Nothing
1048  */
1049 static void sig_pri_handle_subcmds(struct sig_pri_pri *pri, int chanpos, int event_id,
1050         int channel, const struct pri_subcommands *subcmds)
1051 {
1052         int index;
1053         struct ast_channel *owner;
1054
1055         if (!subcmds) {
1056                 return;
1057         }
1058         for (index = 0; index < subcmds->counter_subcmd; ++index) {
1059                 const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
1060
1061                 switch (subcmd->cmd) {
1062                 case PRI_SUBCMD_CONNECTED_LINE:
1063                         sig_pri_lock_owner(pri, chanpos);
1064                         owner = pri->pvts[chanpos]->owner;
1065                         if (owner) {
1066                                 struct ast_party_connected_line ast_connected;
1067                                 const struct pri_party_connected_line *pri_connected;
1068                                 int caller_id_update;
1069                                 char connected_number[AST_MAX_EXTENSION];
1070
1071                                 caller_id_update = 0;
1072
1073                                 /* Extract the connected line information */
1074                                 ast_party_connected_line_init(&ast_connected);
1075                                 pri_connected = &subcmd->u.connected_line;
1076                                 if (pri_connected->id.name.valid) {
1077                                         ast_connected.id.name = (char *) pri_connected->id.name.str;
1078
1079                                         /* Save name for Caller-ID update */
1080                                         ast_copy_string(pri->pvts[chanpos]->cid_name,
1081                                                 pri_connected->id.name.str,
1082                                                 sizeof(pri->pvts[chanpos]->cid_name));
1083                                         caller_id_update = 1;
1084                                 }
1085                                 if (pri_connected->id.number.valid) {
1086                                         apply_plan_to_number(connected_number, sizeof(connected_number), pri,
1087                                                 pri_connected->id.number.str,
1088                                                 pri_connected->id.number.plan);
1089                                         ast_connected.id.number = connected_number;
1090                                         ast_connected.id.number_type = pri_connected->id.number.plan;
1091
1092                                         /* Save number for Caller-ID update */
1093                                         ast_copy_string(pri->pvts[chanpos]->cid_num, connected_number,
1094                                                 sizeof(pri->pvts[chanpos]->cid_num));
1095                                         pri->pvts[chanpos]->cid_ton = pri_connected->id.number.plan;
1096                                         caller_id_update = 1;
1097                                 } else {
1098                                         ast_connected.id.number = "";
1099                                 }
1100                                 if (pri_connected->id.name.valid
1101                                         || pri_connected->id.number.valid) {
1102                                         ast_connected.id.number_presentation =
1103                                                 overall_ast_presentation(&pri_connected->id);
1104                                 }
1105                                 ast_connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1106
1107                                 if (caller_id_update) {
1108                                         pri->pvts[chanpos]->callingpres =
1109                                                 ast_connected.id.number_presentation;
1110                                         sig_pri_set_caller_id(pri->pvts[chanpos]);
1111                                         ast_set_callerid(owner, S_OR(ast_connected.id.number, NULL),
1112                                                 S_OR(ast_connected.id.name, NULL),
1113                                                 S_OR(ast_connected.id.number, NULL));
1114                                 }
1115
1116                                 /* Update the connected line information on the other channel */
1117                                 if (event_id != PRI_EVENT_RING) {
1118                                         /* This connected_line update was not from a SETUP message. */
1119                                         ast_channel_queue_connected_line_update(owner, &ast_connected);
1120                                 }
1121
1122                                 ast_channel_unlock(owner);
1123                         }
1124                         break;
1125                 case PRI_SUBCMD_REDIRECTING:
1126                         sig_pri_lock_owner(pri, chanpos);
1127                         owner = pri->pvts[chanpos]->owner;
1128                         if (owner) {
1129                                 struct ast_party_redirecting ast_redirecting;
1130                                 const struct pri_party_redirecting *pri_redirecting;
1131                                 char from_number[AST_MAX_EXTENSION];
1132                                 char to_number[AST_MAX_EXTENSION];
1133
1134                                 ast_party_redirecting_set_init(&ast_redirecting, &owner->redirecting);
1135
1136                                 pri_redirecting = &subcmd->u.redirecting;
1137
1138                                 /* ast_redirecting.from */
1139                                 if (pri_redirecting->from.name.valid) {
1140                                         ast_redirecting.from.name = (char *) pri_redirecting->from.name.str;
1141                                 }
1142                                 if (pri_redirecting->from.number.valid) {
1143                                         apply_plan_to_number(from_number, sizeof(from_number), pri,
1144                                                 pri_redirecting->from.number.str,
1145                                                 pri_redirecting->from.number.plan);
1146                                         ast_redirecting.from.number = from_number;
1147                                         ast_redirecting.from.number_type = pri_redirecting->from.number.plan;
1148                                 }
1149                                 if (pri_redirecting->from.name.valid
1150                                         || pri_redirecting->from.number.valid) {
1151                                         ast_redirecting.from.number_presentation =
1152                                                 overall_ast_presentation(&pri_redirecting->from);
1153                                 }
1154
1155                                 /* ast_redirecting.to */
1156                                 if (pri_redirecting->to.name.valid) {
1157                                         ast_redirecting.to.name = (char *) pri_redirecting->to.name.str;
1158                                 }
1159                                 if (pri_redirecting->to.number.valid) {
1160                                         apply_plan_to_number(to_number, sizeof(to_number), pri,
1161                                                 pri_redirecting->to.number.str, pri_redirecting->to.number.plan);
1162                                         ast_redirecting.to.number = to_number;
1163                                         ast_redirecting.to.number_type = pri_redirecting->to.number.plan;
1164                                 }
1165                                 if (pri_redirecting->to.name.valid
1166                                         || pri_redirecting->to.number.valid) {
1167                                         ast_redirecting.to.number_presentation =
1168                                                 overall_ast_presentation(&pri_redirecting->from);
1169                                 }
1170
1171                                 ast_redirecting.count = pri_redirecting->count;
1172                                 ast_redirecting.reason = pri_to_ast_reason(pri_redirecting->reason);
1173
1174 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
1175
1176                                 ast_channel_set_redirecting(owner, &ast_redirecting);
1177                                 if (event_id != PRI_EVENT_RING) {
1178                                         /* This redirection was not from a SETUP message. */
1179                                         ast_channel_queue_redirecting_update(owner, &ast_redirecting);
1180                                 }
1181
1182                                 ast_channel_unlock(owner);
1183                         }
1184                         break;
1185                 default:
1186                         ast_debug(2,
1187                                 "Unknown call subcommand(%d) in %s event on channel %d/%d on span %d.\n",
1188                                 subcmd->cmd, pri_event2str(event_id), PRI_SPAN(channel),
1189                                 PRI_CHANNEL(channel), pri->span);
1190                         break;
1191                 }
1192         }
1193 }
1194
1195 static void *pri_dchannel(void *vpri)
1196 {
1197         struct sig_pri_pri *pri = vpri;
1198         pri_event *e;
1199         struct pollfd fds[NUM_DCHANS];
1200         int res;
1201         int chanpos = 0;
1202         int x;
1203         struct ast_channel *c;
1204         struct timeval tv, lowest, *next;
1205         int doidling=0;
1206         char *cc;
1207         time_t t;
1208         int i, which=-1;
1209         int numdchans;
1210         pthread_t threadid;
1211         char ani2str[6];
1212         char plancallingnum[AST_MAX_EXTENSION];
1213         char plancallingani[AST_MAX_EXTENSION];
1214         char calledtonstr[10];
1215         struct timeval lastidle = { 0, 0 };
1216         pthread_t p;
1217         struct ast_channel *idle;
1218         char idlen[80];
1219         int nextidle = -1;
1220         int haveidles;
1221         int activeidles;
1222
1223         gettimeofday(&lastidle, NULL);
1224         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
1225
1226         if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
1227                 /* Need to do idle dialing, check to be sure though */
1228                 cc = strchr(pri->idleext, '@');
1229                 if (cc) {
1230                         *cc = '\0';
1231                         cc++;
1232                         ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
1233 #if 0
1234                         /* Extensions may not be loaded yet */
1235                         if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
1236                                 ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
1237                         else
1238 #endif
1239                                 doidling = 1;
1240                 } else
1241                         ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
1242         }
1243         for (;;) {
1244                 for (i = 0; i < NUM_DCHANS; i++) {
1245                         if (!pri->dchans[i])
1246                                 break;
1247                         fds[i].fd = pri->fds[i];
1248                         fds[i].events = POLLIN | POLLPRI;
1249                         fds[i].revents = 0;
1250                 }
1251                 numdchans = i;
1252                 time(&t);
1253                 ast_mutex_lock(&pri->lock);
1254                 if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->sig != SIG_BRI_PTMP) && (pri->resetinterval > 0)) {
1255                         if (pri->resetting && pri_is_up(pri)) {
1256                                 if (pri->resetpos < 0)
1257                                         pri_check_restart(pri);
1258                         } else {
1259                                 if (!pri->resetting     && (t - pri->lastreset) >= pri->resetinterval) {
1260                                         pri->resetting = 1;
1261                                         pri->resetpos = -1;
1262                                 }
1263                         }
1264                 }
1265                 /* Look for any idle channels if appropriate */
1266                 if (doidling && pri_is_up(pri)) {
1267                         nextidle = -1;
1268                         haveidles = 0;
1269                         activeidles = 0;
1270                         for (x = pri->numchans; x >= 0; x--) {
1271                                 if (pri->pvts[x] && !pri->pvts[x]->owner &&
1272                                         !pri->pvts[x]->call) {
1273                                         if (haveidles < pri->minunused) {
1274                                                 haveidles++;
1275                                         } else if (!pri->pvts[x]->resetting) {
1276                                                 nextidle = x;
1277                                                 break;
1278                                         }
1279                                 } else if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall)
1280                                         activeidles++;
1281                         }
1282                         if (nextidle > -1) {
1283                                 if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
1284                                         /* Don't create a new idle call more than once per second */
1285                                         snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
1286                                         idle = sig_pri_request(pri->pvts[nextidle], AST_FORMAT_ULAW, NULL);
1287                                         if (idle) {
1288                                                 pri->pvts[nextidle]->isidlecall = 1;
1289                                                 if (ast_pthread_create_background(&p, NULL, do_idle_thread, idle)) {
1290                                                         ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
1291                                                         ast_hangup(idle);
1292                                                 }
1293                                         } else
1294                                                 ast_log(LOG_WARNING, "Unable to request channel 'DAHDI/%s' for idle call\n", idlen);
1295                                         gettimeofday(&lastidle, NULL);
1296                                 }
1297                         } else if ((haveidles < pri->minunused) &&
1298                                 (activeidles > pri->minidle)) {
1299                                 /* Mark something for hangup if there is something
1300                                    that can be hungup */
1301                                 for (x = pri->numchans; x >= 0; x--) {
1302                                         /* find a candidate channel */
1303                                         if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
1304                                                 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1305                                                 haveidles++;
1306                                                 /* Stop if we have enough idle channels or
1307                                                   can't spare any more active idle ones */
1308                                                 if ((haveidles >= pri->minunused) ||
1309                                                         (activeidles <= pri->minidle))
1310                                                         break;
1311                                         }
1312                                 }
1313                         }
1314                 }
1315                 /* Start with reasonable max */
1316                 lowest = ast_tv(60, 0);
1317                 for (i = 0; i < NUM_DCHANS; i++) {
1318                         /* Find lowest available d-channel */
1319                         if (!pri->dchans[i])
1320                                 break;
1321                         if ((next = pri_schedule_next(pri->dchans[i]))) {
1322                                 /* We need relative time here */
1323                                 tv = ast_tvsub(*next, ast_tvnow());
1324                                 if (tv.tv_sec < 0) {
1325                                         tv = ast_tv(0,0);
1326                                 }
1327                                 if (doidling || pri->resetting) {
1328                                         if (tv.tv_sec > 1) {
1329                                                 tv = ast_tv(1, 0);
1330                                         }
1331                                 } else {
1332                                         if (tv.tv_sec > 60) {
1333                                                 tv = ast_tv(60, 0);
1334                                         }
1335                                 }
1336                         } else if (doidling || pri->resetting) {
1337                                 /* Make sure we stop at least once per second if we're
1338                                    monitoring idle channels */
1339                                 tv = ast_tv(1,0);
1340                         } else {
1341                                 /* Don't poll for more than 60 seconds */
1342                                 tv = ast_tv(60, 0);
1343                         }
1344                         if (!i || ast_tvcmp(tv, lowest) < 0) {
1345                                 lowest = tv;
1346                         }
1347                 }
1348                 ast_mutex_unlock(&pri->lock);
1349
1350                 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
1351                 pthread_testcancel();
1352                 e = NULL;
1353                 res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
1354                 pthread_testcancel();
1355                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
1356
1357                 ast_mutex_lock(&pri->lock);
1358                 if (!res) {
1359                         for (which = 0; which < NUM_DCHANS; which++) {
1360                                 if (!pri->dchans[which])
1361                                         break;
1362                                 /* Just a timeout, run the scheduler */
1363                                 e = pri_schedule_run(pri->dchans[which]);
1364                                 if (e)
1365                                         break;
1366                         }
1367                 } else if (res > -1) {
1368                         for (which = 0; which < NUM_DCHANS; which++) {
1369                                 if (!pri->dchans[which])
1370                                         break;
1371                                 if (fds[which].revents & POLLPRI) {
1372                                         sig_pri_handle_dchan_exception(pri, which);
1373                                 } else if (fds[which].revents & POLLIN) {
1374                                         e = pri_check_event(pri->dchans[which]);
1375                                 }
1376                                 if (e)
1377                                         break;
1378                         }
1379                 } else if (errno != EINTR)
1380                         ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
1381
1382                 if (e) {
1383                         if (pri->debug)
1384                                 pri_dump_event(pri->dchans[which], e);
1385
1386                         if (e->e != PRI_EVENT_DCHAN_DOWN) {
1387                                 if (!(pri->dchanavail[which] & DCHAN_UP)) {
1388                                         ast_verb(2, "%s D-Channel on span %d up\n", pri_order(which), pri->span);
1389                                 }
1390                                 pri->dchanavail[which] |= DCHAN_UP;
1391                         } else {
1392                                 if (pri->dchanavail[which] & DCHAN_UP) {
1393                                         ast_verb(2, "%s D-Channel on span %d down\n", pri_order(which), pri->span);
1394                                 }
1395                                 pri->dchanavail[which] &= ~DCHAN_UP;
1396                         }
1397
1398                         if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
1399                                 /* Must be an NFAS group that has the secondary dchan active */
1400                                 pri->pri = pri->dchans[which];
1401
1402                         switch (e->e) {
1403                         case PRI_EVENT_DCHAN_UP:
1404                                 if (!pri->pri) pri_find_dchan(pri);
1405
1406                                 /* Note presense of D-channel */
1407                                 time(&pri->lastreset);
1408
1409                                 /* Restart in 5 seconds */
1410                                 if (pri->resetinterval > -1) {
1411                                         pri->lastreset -= pri->resetinterval;
1412                                         pri->lastreset += 5;
1413                                 }
1414                                 pri->resetting = 0;
1415                                 /* Take the channels from inalarm condition */
1416                                 for (i = 0; i < pri->numchans; i++)
1417                                         if (pri->pvts[i]) {
1418                                                 pri->pvts[i]->inalarm = 0;
1419                                         }
1420                                 break;
1421                         case PRI_EVENT_DCHAN_DOWN:
1422                                 pri_find_dchan(pri);
1423                                 if (!pri_is_up(pri)) {
1424                                         pri->resetting = 0;
1425                                         /* Hangup active channels and put them in alarm mode */
1426                                         for (i = 0; i < pri->numchans; i++) {
1427                                                 struct sig_pri_chan *p = pri->pvts[i];
1428                                                 if (p) {
1429                                                         if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
1430                                                                 /* T309 is not enabled : hangup calls when alarm occurs */
1431                                                                 if (p->call) {
1432                                                                         if (p->pri && p->pri->pri) {
1433                                                                                 pri_hangup(p->pri->pri, p->call, -1);
1434                                                                                 pri_destroycall(p->pri->pri, p->call);
1435                                                                                 p->call = NULL;
1436                                                                         } else
1437                                                                                 ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
1438                                                                 }
1439                                                                 if (p->owner)
1440                                                                         ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
1441                                                         }
1442                                                         /* For PTMP connections with non persistent layer 2 we want
1443                                                          * to *not* declare inalarm unless there actually is an alarm */
1444                                                         if (p->pri->sig != SIG_BRI_PTMP) {
1445                                                                 p->inalarm = 1;
1446                                                         }
1447                                                 }
1448                                         }
1449                                 }
1450                                 break;
1451                         case PRI_EVENT_RESTART:
1452                                 if (e->restart.channel > -1) {
1453                                         chanpos = pri_find_principle(pri, e->restart.channel);
1454                                         if (chanpos < 0)
1455                                                 ast_log(LOG_WARNING, "Restart requested on odd/unavailable channel number %d/%d on span %d\n",
1456                                                         PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
1457                                         else {
1458 #ifdef HAVE_PRI_SERVICE_MESSAGES
1459                                                 char db_chan_name[20], db_answer[5], state;
1460                                                 int why, skipit = 0;
1461
1462                                                 ast_mutex_lock(&pri->pvts[chanpos]->service_lock);
1463                                                 snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->pvts[chanpos]->pri->span, pri->pvts[chanpos]->channel);
1464                                                 ast_mutex_unlock(&pri->pvts[chanpos]->service_lock);
1465
1466                                                 if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
1467                                                         sscanf(db_answer, "%1c:%30d", &state, &why);
1468                                                         if (why) {
1469                                                                 ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), ignoring RESTART\n", pri->span,
1470                                                                         e->restart.channel, (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
1471                                                                 skipit = 1;
1472                                                         } else {
1473                                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
1474                                                         }
1475                                                 }
1476                                                 if (!skipit) {
1477 #endif
1478                                                         ast_verb(3, "B-channel %d/%d restarted on span %d\n",
1479                                                                 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
1480                                                         sig_pri_lock_private(pri->pvts[chanpos]);
1481                                                         if (pri->pvts[chanpos]->call) {
1482                                                                 pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
1483                                                                 pri->pvts[chanpos]->call = NULL;
1484                                                         }
1485 #ifdef HAVE_PRI_SERVICE_MESSAGES
1486                                                 }
1487 #endif
1488                                                 /* Force soft hangup if appropriate */
1489                                                 if (pri->pvts[chanpos]->owner)
1490                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
1491                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1492                                         }
1493                                 } else {
1494                                         ast_verb(3, "Restart on requested on entire span %d\n", pri->span);
1495                                         for (x = 0; x < pri->numchans; x++)
1496                                                 if (pri->pvts[x]) {
1497                                                         sig_pri_lock_private(pri->pvts[x]);
1498                                                         if (pri->pvts[x]->call) {
1499                                                                 pri_destroycall(pri->pri, pri->pvts[x]->call);
1500                                                                 pri->pvts[x]->call = NULL;
1501                                                         }
1502                                                         if (pri->pvts[x]->owner)
1503                                                                 ast_softhangup_nolock(pri->pvts[x]->owner, AST_SOFTHANGUP_DEV);
1504                                                         sig_pri_unlock_private(pri->pvts[x]);
1505                                                 }
1506                                 }
1507                                 break;
1508                         case PRI_EVENT_KEYPAD_DIGIT:
1509                                 chanpos = pri_find_principle(pri, e->digit.channel);
1510                                 if (chanpos < 0) {
1511                                         ast_log(LOG_WARNING, "KEYPAD_DIGITs received on unconfigured channel %d/%d span %d\n",
1512                                                 PRI_SPAN(e->digit.channel), PRI_CHANNEL(e->digit.channel), pri->span);
1513                                 } else {
1514                                         chanpos = pri_fixup_principle(pri, chanpos, e->digit.call);
1515                                         if (chanpos > -1) {
1516                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1517                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->digit.channel,
1518                                                         e->digit.subcmds);
1519                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
1520                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
1521                                                         && pri->pvts[chanpos]->call == e->digit.call
1522                                                         && pri->pvts[chanpos]->owner) {
1523                                                         /* how to do that */
1524                                                         int digitlen = strlen(e->digit.digits);
1525                                                         int i;
1526
1527                                                         for (i = 0; i < digitlen; i++) {
1528                                                                 struct ast_frame f = { AST_FRAME_DTMF, e->digit.digits[i], };
1529
1530                                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1531                                                         }
1532                                                 }
1533                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1534                                         }
1535                                 }
1536                                 break;
1537
1538                         case PRI_EVENT_INFO_RECEIVED:
1539                                 chanpos = pri_find_principle(pri, e->ring.channel);
1540                                 if (chanpos < 0) {
1541                                         ast_log(LOG_WARNING, "INFO received on unconfigured channel %d/%d span %d\n",
1542                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
1543                                 } else {
1544                                         chanpos = pri_fixup_principle(pri, chanpos, e->ring.call);
1545                                         if (chanpos > -1) {
1546                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1547                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
1548                                                         e->ring.subcmds);
1549                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
1550                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
1551                                                         && pri->pvts[chanpos]->call == e->ring.call
1552                                                         && pri->pvts[chanpos]->owner) {
1553                                                         /* how to do that */
1554                                                         int digitlen = strlen(e->ring.callednum);
1555                                                         int i;
1556
1557                                                         for (i = 0; i < digitlen; i++) {
1558                                                                 struct ast_frame f = { AST_FRAME_DTMF, e->ring.callednum[i], };
1559
1560                                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1561                                                         }
1562                                                 }
1563                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1564                                         }
1565                                 }
1566                                 break;
1567 #ifdef HAVE_PRI_SERVICE_MESSAGES
1568                         case PRI_EVENT_SERVICE:
1569                                 chanpos = pri_find_principle(pri, e->service.channel);
1570                                 if (chanpos < 0) {
1571                                         ast_log(LOG_WARNING, "Received service change status %d on unconfigured channel %d/%d span %d\n",
1572                                                 e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
1573                                 } else {
1574                                         char db_chan_name[20], db_answer[5], state;
1575                                         int ch, why = -1;
1576
1577                                         ast_mutex_lock(&pri->pvts[chanpos]->service_lock);
1578                                         ch = pri->pvts[chanpos]->channel;
1579                                         ast_mutex_unlock(&pri->pvts[chanpos]->service_lock);
1580
1581                                         snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->pvts[chanpos]->pri->span, ch);
1582                                         if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
1583                                                 sscanf(db_answer, "%1c:%30d", &state, &why);
1584                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
1585                                         }
1586                                         switch (e->service.changestatus) {
1587                                         case 0: /* in-service */
1588                                                 if (why > -1) {
1589                                                         if (why & SRVST_NEAREND) {
1590                                                                 snprintf(db_answer, sizeof(db_answer), "%s:%d", SRVST_TYPE_OOS, SRVST_NEAREND);
1591                                                                 ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
1592                                                                 ast_debug(2, "channel '%d' service state { near: out-of-service,  far: in-service }\n", ch);
1593                                                         }
1594                                                 }
1595                                                 break;
1596                                         case 2: /* out-of-service */
1597                                                 if (why == -1) {
1598                                                         why = SRVST_FAREND;
1599                                                 } else {
1600                                                         why |= SRVST_FAREND;
1601                                                 }
1602                                                 snprintf(db_answer, sizeof(db_answer), "%s:%d", SRVST_TYPE_OOS, why);
1603                                                 ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
1604                                                 break;
1605                                         default:
1606                                                 ast_log(LOG_ERROR, "Huh?  changestatus is: %d\n", e->service.changestatus);
1607                                         }
1608                                         ast_log(LOG_NOTICE, "Channel %d/%d span %d (logical: %d) received a change of service message, status '%d'\n",
1609                                                 PRI_SPAN(e->service.channel), PRI_CHANNEL(e->service.channel), pri->span, ch, e->service.changestatus);
1610                                 }
1611                                 break;
1612                         case PRI_EVENT_SERVICE_ACK:
1613                                 chanpos = pri_find_principle(pri, e->service_ack.channel);
1614                                 if (chanpos < 0) {
1615                                         ast_log(LOG_WARNING, "Received service acknowledge change status '%d' on unconfigured channel %d/%d span %d\n",
1616                                                 e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
1617                                 } else {
1618                                         ast_debug(2, "Channel %d/%d span %d received a change os service acknowledgement message, status '%d'\n",
1619                                                 PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span, e->service_ack.changestatus);
1620                                 }
1621                                 break;
1622 #endif
1623                         case PRI_EVENT_RING:
1624                                 if (e->ring.channel == -1)
1625                                         chanpos = pri_find_empty_chan(pri, 1);
1626                                 else
1627                                         chanpos = pri_find_principle(pri, e->ring.channel);
1628                                 /* if no channel specified find one empty */
1629                                 if (chanpos < 0) {
1630                                         ast_log(LOG_WARNING, "Ring requested on unconfigured channel %d/%d span %d\n",
1631                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
1632                                 } else {
1633                                         sig_pri_lock_private(pri->pvts[chanpos]);
1634                                         if (pri->pvts[chanpos]->owner) {
1635                                                 if (pri->pvts[chanpos]->call == e->ring.call) {
1636                                                         ast_log(LOG_WARNING, "Duplicate setup requested on channel %d/%d already in use on span %d\n",
1637                                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
1638                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1639                                                         break;
1640                                                 } else {
1641                                                         /* This is where we handle initial glare */
1642                                                         ast_debug(1, "Ring requested on channel %d/%d already in use or previously requested on span %d.  Attempting to renegotiating channel.\n",
1643                                                         PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
1644                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1645                                                         chanpos = -1;
1646                                                 }
1647                                         }
1648                                         if (chanpos > -1)
1649                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1650                                 }
1651                                 if ((chanpos < 0) && (e->ring.flexible))
1652                                         chanpos = pri_find_empty_chan(pri, 1);
1653                                 if (chanpos > -1) {
1654                                         sig_pri_lock_private(pri->pvts[chanpos]);
1655                                         pri->pvts[chanpos]->call = e->ring.call;
1656
1657                                         /* Use plancallingnum as a scratch buffer since it is initialized next. */
1658                                         apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri,
1659                                                 e->ring.redirectingnum, e->ring.callingplanrdnis);
1660                                         sig_pri_set_rdnis(pri->pvts[chanpos], plancallingnum);
1661
1662                                         /* Setup caller-id info */
1663                                         apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri, e->ring.callingnum, e->ring.callingplan);
1664                                         pri->pvts[chanpos]->cid_ani2 = 0;
1665                                         if (pri->pvts[chanpos]->use_callerid) {
1666                                                 ast_shrink_phone_number(plancallingnum);
1667                                                 ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
1668 #ifdef PRI_ANI
1669                                                 if (!ast_strlen_zero(e->ring.callingani)) {
1670                                                         apply_plan_to_number(plancallingani, sizeof(plancallingani), pri, e->ring.callingani, e->ring.callingplanani);
1671                                                         ast_shrink_phone_number(plancallingani);
1672                                                         ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani, sizeof(pri->pvts[chanpos]->cid_ani));
1673                                                 } else {
1674                                                         pri->pvts[chanpos]->cid_ani[0] = '\0';
1675                                                 }
1676 #endif
1677                                                 ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
1678                                                 pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
1679                                                 pri->pvts[chanpos]->callingpres = e->ring.callingpres;
1680                                                 if (e->ring.ani2 >= 0) {
1681                                                         pri->pvts[chanpos]->cid_ani2 = e->ring.ani2;
1682                                                 }
1683                                         } else {
1684                                                 pri->pvts[chanpos]->cid_num[0] = '\0';
1685                                                 pri->pvts[chanpos]->cid_ani[0] = '\0';
1686                                                 pri->pvts[chanpos]->cid_name[0] = '\0';
1687                                                 pri->pvts[chanpos]->cid_ton = 0;
1688                                                 pri->pvts[chanpos]->callingpres = 0;
1689                                         }
1690                                         sig_pri_set_caller_id(pri->pvts[chanpos]);
1691
1692                                         /* Set DNID on all incoming calls -- even immediate */
1693                                         sig_pri_set_dnid(pri->pvts[chanpos], e->ring.callednum);
1694
1695                                         /* If immediate=yes go to s|1 */
1696                                         if (pri->pvts[chanpos]->immediate) {
1697                                                 ast_verb(3, "Going to extension s|1 because of immediate=yes\n");
1698                                                 pri->pvts[chanpos]->exten[0] = 's';
1699                                                 pri->pvts[chanpos]->exten[1] = '\0';
1700                                         }
1701                                         /* Get called number */
1702                                         else if (!ast_strlen_zero(e->ring.callednum)) {
1703                                                 ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
1704                                         } else if (pri->overlapdial)
1705                                                 pri->pvts[chanpos]->exten[0] = '\0';
1706                                         else {
1707                                                 /* Some PRI circuits are set up to send _no_ digits.  Handle them as 's'. */
1708                                                 pri->pvts[chanpos]->exten[0] = 's';
1709                                                 pri->pvts[chanpos]->exten[1] = '\0';
1710                                         }
1711                                         /* No number yet, but received "sending complete"? */
1712                                         if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
1713                                                 ast_verb(3, "Going to extension s|1 because of Complete received\n");
1714                                                 pri->pvts[chanpos]->exten[0] = 's';
1715                                                 pri->pvts[chanpos]->exten[1] = '\0';
1716                                         }
1717
1718                                         /* Make sure extension exists (or in overlap dial mode, can exist) */
1719                                         if (((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
1720                                                 ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
1721                                                 /* Setup law */
1722                                                 if (e->ring.complete || !(pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
1723                                                         /* Just announce proceeding */
1724                                                         pri->pvts[chanpos]->proceeding = 1;
1725                                                         pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
1726                                                 } else {
1727                                                         if (pri->switchtype != PRI_SWITCH_GR303_TMC)
1728                                                                 pri_need_more_info(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
1729                                                         else
1730                                                                 pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
1731                                                 }
1732
1733                                                 /* Start PBX */
1734                                                 if (!e->ring.complete
1735                                                         && (pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
1736                                                         && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
1737                                                         /*
1738                                                          * Release the PRI lock while we create the channel
1739                                                          * so other threads can send D channel messages.
1740                                                          */
1741                                                         ast_mutex_unlock(&pri->lock);
1742                                                         c = sig_pri_new_ast_channel(pri->pvts[chanpos],
1743                                                                 AST_STATE_RESERVED, 0,
1744                                                                 (e->ring.layer1 == PRI_LAYER_1_ALAW)
1745                                                                         ? SIG_PRI_ALAW : SIG_PRI_ULAW,
1746                                                                 e->ring.ctype, pri->pvts[chanpos]->exten, NULL);
1747                                                         ast_mutex_lock(&pri->lock);
1748                                                         if (c) {
1749                                                                 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
1750                                                                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
1751                                                                 }
1752                                                                 if (e->ring.ani2 >= 0) {
1753                                                                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
1754                                                                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
1755                                                                 }
1756
1757 #ifdef SUPPORT_USERUSER
1758                                                                 if (!ast_strlen_zero(e->ring.useruserinfo)) {
1759                                                                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
1760                                                                 }
1761 #endif
1762
1763                                                                 snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
1764                                                                 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
1765                                                                 if (e->ring.redirectingreason >= 0) {
1766                                                                         /* This is now just a status variable.  Use REDIRECTING() dialplan function. */
1767                                                                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
1768                                                                 }
1769 #if defined(HAVE_PRI_REVERSE_CHARGE)
1770                                                                 pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
1771 #endif
1772
1773                                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
1774                                                                         e->ring.subcmds);
1775                                                         }
1776                                                         if (c && !ast_pthread_create_detached(&threadid, NULL, pri_ss_thread, pri->pvts[chanpos])) {
1777                                                                 ast_verb(3, "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
1778                                                                         plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
1779                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
1780                                                         } else {
1781                                                                 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
1782                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
1783                                                                 if (c)
1784                                                                         ast_hangup(c);
1785                                                                 else {
1786                                                                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
1787                                                                         pri->pvts[chanpos]->call = NULL;
1788                                                                 }
1789                                                         }
1790                                                 } else {
1791                                                         /*
1792                                                          * Release the PRI lock while we create the channel
1793                                                          * so other threads can send D channel messages.
1794                                                          */
1795                                                         ast_mutex_unlock(&pri->lock);
1796                                                         c = sig_pri_new_ast_channel(pri->pvts[chanpos],
1797                                                                 AST_STATE_RING, 0,
1798                                                                 (e->ring.layer1 == PRI_LAYER_1_ALAW)
1799                                                                         ? SIG_PRI_ALAW : SIG_PRI_ULAW, e->ring.ctype,
1800                                                                 pri->pvts[chanpos]->exten, NULL);
1801                                                         ast_mutex_lock(&pri->lock);
1802                                                         if (c) {
1803                                                                 /*
1804                                                                  * It is reasonably safe to set the following
1805                                                                  * channel variables while the PRI and DAHDI private
1806                                                                  * structures are locked.  The PBX has not been
1807                                                                  * started yet and it is unlikely that any other task
1808                                                                  * will do anything with the channel we have just
1809                                                                  * created.
1810                                                                  */
1811                                                                 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
1812                                                                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
1813                                                                 }
1814                                                                 if (e->ring.ani2 >= 0) {
1815                                                                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
1816                                                                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
1817                                                                 }
1818
1819 #ifdef SUPPORT_USERUSER
1820                                                                 if (!ast_strlen_zero(e->ring.useruserinfo)) {
1821                                                                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
1822                                                                 }
1823 #endif
1824
1825                                                                 if (e->ring.redirectingreason >= 0) {
1826                                                                         /* This is now just a status variable.  Use REDIRECTING() dialplan function. */
1827                                                                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
1828                                                                 }
1829 #if defined(HAVE_PRI_REVERSE_CHARGE)
1830                                                                 pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
1831 #endif
1832
1833                                                                 snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
1834                                                                 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
1835
1836                                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
1837                                                                         e->ring.subcmds);
1838                                                         }
1839                                                         if (c && !ast_pbx_start(c)) {
1840                                                                 ast_verb(3, "Accepting call from '%s' to '%s' on channel %d/%d, span %d\n",
1841                                                                         plancallingnum, pri->pvts[chanpos]->exten,
1842                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
1843                                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
1844                                                         } else {
1845                                                                 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
1846                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
1847                                                                 if (c) {
1848                                                                         ast_hangup(c);
1849                                                                 } else {
1850                                                                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
1851                                                                         pri->pvts[chanpos]->call = NULL;
1852                                                                 }
1853                                                         }
1854                                                 }
1855                                         } else {
1856                                                 ast_verb(3, "Extension '%s' in context '%s' from '%s' does not exist.  Rejecting call on channel %d/%d, span %d\n",
1857                                                         pri->pvts[chanpos]->exten, pri->pvts[chanpos]->context, pri->pvts[chanpos]->cid_num, pri->pvts[chanpos]->logicalspan,
1858                                                         pri->pvts[chanpos]->prioffset, pri->span);
1859                                                 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_UNALLOCATED);
1860                                                 pri->pvts[chanpos]->call = NULL;
1861                                                 pri->pvts[chanpos]->exten[0] = '\0';
1862                                         }
1863                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1864                                 } else {
1865                                         if (e->ring.flexible)
1866                                                 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
1867                                         else
1868                                                 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
1869                                 }
1870                                 break;
1871                         case PRI_EVENT_RINGING:
1872                                 chanpos = pri_find_principle(pri, e->ringing.channel);
1873                                 if (chanpos < 0) {
1874                                         ast_log(LOG_WARNING, "Ringing requested on unconfigured channel %d/%d span %d\n",
1875                                                 PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
1876                                 } else {
1877                                         chanpos = pri_fixup_principle(pri, chanpos, e->ringing.call);
1878                                         if (chanpos < 0) {
1879                                                 ast_log(LOG_WARNING, "Ringing requested on channel %d/%d not in use on span %d\n",
1880                                                         PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
1881                                         } else {
1882                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1883
1884                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ringing.channel,
1885                                                         e->ringing.subcmds);
1886                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
1887                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_RINGING, pri);
1888                                                 pri->pvts[chanpos]->alerting = 1;
1889
1890 #ifdef SUPPORT_USERUSER
1891                                                 if (!ast_strlen_zero(e->ringing.useruserinfo)) {
1892                                                         struct ast_channel *owner;
1893
1894                                                         sig_pri_lock_owner(pri, chanpos);
1895                                                         owner = pri->pvts[chanpos]->owner;
1896                                                         if (owner) {
1897                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
1898                                                                         e->ringing.useruserinfo);
1899                                                                 ast_channel_unlock(owner);
1900                                                         }
1901                                                 }
1902 #endif
1903
1904                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1905                                         }
1906                                 }
1907                                 break;
1908                         case PRI_EVENT_PROGRESS:
1909                                 /* Get chan value if e->e is not PRI_EVNT_RINGING */
1910                                 chanpos = pri_find_principle(pri, e->proceeding.channel);
1911                                 if (chanpos > -1) {
1912                                         sig_pri_lock_private(pri->pvts[chanpos]);
1913                                         sig_pri_handle_subcmds(pri, chanpos, e->e, e->proceeding.channel,
1914                                                 e->proceeding.subcmds);
1915                                         if ((!pri->pvts[chanpos]->progress)
1916 #ifdef PRI_PROGRESS_MASK
1917                                                 || (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE)
1918 #else
1919                                                 || (e->proceeding.progress == 8)
1920 #endif
1921                                                 ) {
1922                                                 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, };
1923
1924                                                 if (e->proceeding.cause > -1) {
1925                                                         ast_verb(3, "PROGRESS with cause code %d received\n", e->proceeding.cause);
1926
1927                                                         /* Work around broken, out of spec USER_BUSY cause in a progress message */
1928                                                         if (e->proceeding.cause == AST_CAUSE_USER_BUSY) {
1929                                                                 if (pri->pvts[chanpos]->owner) {
1930                                                                         ast_verb(3, "PROGRESS with 'user busy' received, signaling AST_CONTROL_BUSY instead of AST_CONTROL_PROGRESS\n");
1931
1932                                                                         pri->pvts[chanpos]->owner->hangupcause = e->proceeding.cause;
1933                                                                         f.subclass = AST_CONTROL_BUSY;
1934                                                                 }
1935                                                         }
1936                                                 }
1937
1938                                                 ast_debug(1, "Queuing frame from PRI_EVENT_PROGRESS on channel %d/%d span %d\n",
1939                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
1940                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1941                                                 if (
1942 #ifdef PRI_PROGRESS_MASK
1943                                                         e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE
1944 #else
1945                                                         e->proceeding.progress == 8
1946 #endif
1947                                                         ) {
1948                                                         /* Bring voice path up */
1949                                                         f.subclass = AST_CONTROL_PROGRESS;
1950                                                         pri_queue_frame(pri->pvts[chanpos], &f, pri);
1951                                                 }
1952                                                 pri->pvts[chanpos]->progress = 1;
1953                                                 sig_pri_set_dialing(pri->pvts[chanpos], 0);
1954                                         }
1955                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1956                                 }
1957                                 break;
1958                         case PRI_EVENT_PROCEEDING:
1959                                 chanpos = pri_find_principle(pri, e->proceeding.channel);
1960                                 if (chanpos > -1) {
1961                                         sig_pri_lock_private(pri->pvts[chanpos]);
1962                                         sig_pri_handle_subcmds(pri, chanpos, e->e, e->proceeding.channel,
1963                                                 e->proceeding.subcmds);
1964                                         if (!pri->pvts[chanpos]->proceeding) {
1965                                                 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROCEEDING, };
1966
1967                                                 ast_debug(1, "Queuing frame from PRI_EVENT_PROCEEDING on channel %d/%d span %d\n",
1968                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
1969                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1970                                                 if (
1971 #ifdef PRI_PROGRESS_MASK
1972                                                         e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE
1973 #else
1974                                                         e->proceeding.progress == 8
1975 #endif
1976                                                         ) {
1977                                                         /* Bring voice path up */
1978                                                         f.subclass = AST_CONTROL_PROGRESS;
1979                                                         pri_queue_frame(pri->pvts[chanpos], &f, pri);
1980                                                 }
1981                                                 pri->pvts[chanpos]->proceeding = 1;
1982                                                 sig_pri_set_dialing(pri->pvts[chanpos], 0);
1983                                         }
1984                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1985                                 }
1986                                 break;
1987                         case PRI_EVENT_FACILITY:
1988                                 chanpos = pri_find_principle(pri, e->facility.channel);
1989                                 if (chanpos < 0) {
1990                                         ast_log(LOG_WARNING, "Facility requested on unconfigured channel %d/%d span %d\n",
1991                                                 PRI_SPAN(e->facility.channel), PRI_CHANNEL(e->facility.channel), pri->span);
1992                                 } else {
1993                                         chanpos = pri_fixup_principle(pri, chanpos, e->facility.call);
1994                                         if (chanpos < 0) {
1995                                                 ast_log(LOG_WARNING, "Facility requested on channel %d/%d not in use on span %d\n",
1996                                                         PRI_SPAN(e->facility.channel), PRI_CHANNEL(e->facility.channel), pri->span);
1997                                         } else {
1998                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1999                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->facility.channel,
2000                                                         e->facility.subcmds);
2001                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2002                                         }
2003                                 }
2004                                 break;
2005                         case PRI_EVENT_ANSWER:
2006                                 chanpos = pri_find_principle(pri, e->answer.channel);
2007                                 if (chanpos < 0) {
2008                                         ast_log(LOG_WARNING, "Answer on unconfigured channel %d/%d span %d\n",
2009                                                 PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
2010                                 } else {
2011                                         chanpos = pri_fixup_principle(pri, chanpos, e->answer.call);
2012                                         if (chanpos < 0) {
2013                                                 ast_log(LOG_WARNING, "Answer requested on channel %d/%d not in use on span %d\n",
2014                                                         PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
2015                                         } else {
2016                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2017
2018                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->answer.channel,
2019                                                         e->answer.subcmds);
2020                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_ANSWER, pri);
2021                                                 /* Enable echo cancellation if it's not on already */
2022                                                 sig_pri_set_dialing(pri->pvts[chanpos], 0);
2023                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
2024
2025 #ifdef SUPPORT_USERUSER
2026                                                 if (!ast_strlen_zero(e->answer.useruserinfo)) {
2027                                                         struct ast_channel *owner;
2028
2029                                                         sig_pri_lock_owner(pri, chanpos);
2030                                                         owner = pri->pvts[chanpos]->owner;
2031                                                         if (owner) {
2032                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
2033                                                                         e->answer.useruserinfo);
2034                                                                 ast_channel_unlock(owner);
2035                                                         }
2036                                                 }
2037 #endif
2038
2039                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2040                                         }
2041                                 }
2042                                 break;
2043                         case PRI_EVENT_HANGUP:
2044                                 chanpos = pri_find_principle(pri, e->hangup.channel);
2045                                 if (chanpos < 0) {
2046                                         ast_log(LOG_WARNING, "Hangup requested on unconfigured channel %d/%d span %d\n",
2047                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2048                                 } else {
2049                                         chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
2050                                         if (chanpos > -1) {
2051                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2052                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->hangup.channel,
2053                                                         e->hangup.subcmds);
2054                                                 if (!pri->pvts[chanpos]->alreadyhungup) {
2055                                                         /* we're calling here dahdi_hangup so once we get there we need to clear p->call after calling pri_hangup */
2056                                                         pri->pvts[chanpos]->alreadyhungup = 1;
2057                                                         if (pri->pvts[chanpos]->owner) {
2058                                                                 /* Queue a BUSY instead of a hangup if our cause is appropriate */
2059                                                                 pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
2060                                                                 if (pri->pvts[chanpos]->owner->_state == AST_STATE_UP)
2061                                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2062                                                                 else {
2063                                                                         switch (e->hangup.cause) {
2064                                                                         case PRI_CAUSE_USER_BUSY:
2065                                                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_BUSY, pri);
2066                                                                                 break;
2067                                                                         case PRI_CAUSE_CALL_REJECTED:
2068                                                                         case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
2069                                                                         case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
2070                                                                         case PRI_CAUSE_SWITCH_CONGESTION:
2071                                                                         case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
2072                                                                         case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
2073                                                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_CONGESTION, pri);
2074                                                                                 break;
2075                                                                         default:
2076                                                                                 ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2077                                                                                 break;
2078                                                                         }
2079                                                                 }
2080                                                         }
2081                                                         ast_verb(3, "Channel %d/%d, span %d got hangup, cause %d\n",
2082                                                                 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, e->hangup.cause);
2083                                                 } else {
2084                                                         pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
2085                                                         pri->pvts[chanpos]->call = NULL;
2086                                                 }
2087                                                 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
2088                                                         ast_verb(3, "Forcing restart of channel %d/%d on span %d since channel reported in use\n",
2089                                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2090                                                         pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
2091                                                         pri->pvts[chanpos]->resetting = 1;
2092                                                 }
2093                                                 if (e->hangup.aoc_units > -1)
2094                                                         ast_verb(3, "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
2095                                                                 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
2096
2097 #ifdef SUPPORT_USERUSER
2098                                                 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
2099                                                         struct ast_channel *owner;
2100
2101                                                         sig_pri_lock_owner(pri, chanpos);
2102                                                         owner = pri->pvts[chanpos]->owner;
2103                                                         if (owner) {
2104                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
2105                                                                         e->hangup.useruserinfo);
2106                                                                 ast_channel_unlock(owner);
2107                                                         }
2108                                                 }
2109 #endif
2110
2111                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2112                                         } else {
2113                                                 ast_log(LOG_WARNING, "Hangup on bad channel %d/%d on span %d\n",
2114                                                         PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2115                                         }
2116                                 }
2117                                 break;
2118                         case PRI_EVENT_HANGUP_REQ:
2119                                 chanpos = pri_find_principle(pri, e->hangup.channel);
2120                                 if (chanpos < 0) {
2121                                         ast_log(LOG_WARNING, "Hangup REQ requested on unconfigured channel %d/%d span %d\n",
2122                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2123                                 } else {
2124                                         chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
2125                                         if (chanpos > -1) {
2126                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2127                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->hangup.channel,
2128                                                         e->hangup.subcmds);
2129                                                 if (pri->pvts[chanpos]->owner) {
2130                                                         pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
2131                                                         if (pri->pvts[chanpos]->owner->_state == AST_STATE_UP)
2132                                                                 ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2133                                                         else {
2134                                                                 switch (e->hangup.cause) {
2135                                                                 case PRI_CAUSE_USER_BUSY:
2136                                                                         pri_queue_control(pri->pvts[chanpos], AST_CONTROL_BUSY, pri);
2137                                                                         break;
2138                                                                 case PRI_CAUSE_CALL_REJECTED:
2139                                                                 case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
2140                                                                 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
2141                                                                 case PRI_CAUSE_SWITCH_CONGESTION:
2142                                                                 case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
2143                                                                 case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
2144                                                                         pri_queue_control(pri->pvts[chanpos], AST_CONTROL_CONGESTION, pri);
2145                                                                         break;
2146                                                                 default:
2147                                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2148                                                                         break;
2149                                                                 }
2150                                                         }
2151                                                         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);
2152                                                         if (e->hangup.aoc_units > -1)
2153                                                                 ast_verb(3, "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
2154                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
2155                                                 } else {
2156                                                         pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
2157                                                         pri->pvts[chanpos]->call = NULL;
2158                                                 }
2159                                                 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
2160                                                         ast_verb(3, "Forcing restart of channel %d/%d span %d since channel reported in use\n",
2161                                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2162                                                         pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
2163                                                         pri->pvts[chanpos]->resetting = 1;
2164                                                 }
2165
2166 #ifdef SUPPORT_USERUSER
2167                                                 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
2168                                                         struct ast_channel *owner;
2169
2170                                                         sig_pri_lock_owner(pri, chanpos);
2171                                                         owner = pri->pvts[chanpos]->owner;
2172                                                         if (owner) {
2173                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
2174                                                                         e->hangup.useruserinfo);
2175                                                                 ast_channel_unlock(owner);
2176                                                         }
2177                                                 }
2178 #endif
2179
2180                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2181                                         } else {
2182                                                 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);
2183                                         }
2184                                 }
2185                                 break;
2186                         case PRI_EVENT_HANGUP_ACK:
2187                                 chanpos = pri_find_principle(pri, e->hangup.channel);
2188                                 if (chanpos < 0) {
2189                                         ast_log(LOG_WARNING, "Hangup ACK requested on unconfigured channel number %d/%d span %d\n",
2190                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2191                                 } else {
2192                                         chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
2193                                         if (chanpos > -1) {
2194                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2195                                                 pri->pvts[chanpos]->call = NULL;
2196                                                 pri->pvts[chanpos]->resetting = 0;
2197                                                 if (pri->pvts[chanpos]->owner) {
2198                                                         ast_verb(3, "Channel %d/%d, span %d got hangup ACK\n", PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
2199                                                 }
2200
2201 #ifdef SUPPORT_USERUSER
2202                                                 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
2203                                                         struct ast_channel *owner;
2204
2205                                                         sig_pri_lock_owner(pri, chanpos);
2206                                                         owner = pri->pvts[chanpos]->owner;
2207                                                         if (owner) {
2208                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
2209                                                                         e->hangup.useruserinfo);
2210                                                                 ast_channel_unlock(owner);
2211                                                         }
2212                                                 }
2213 #endif
2214
2215                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2216                                         }
2217                                 }
2218                                 break;
2219                         case PRI_EVENT_CONFIG_ERR:
2220                                 ast_log(LOG_WARNING, "PRI Error on span %d: %s\n", pri->trunkgroup, e->err.err);
2221                                 break;
2222                         case PRI_EVENT_RESTART_ACK:
2223                                 chanpos = pri_find_principle(pri, e->restartack.channel);
2224                                 if (chanpos < 0) {
2225                                         /* Sometime switches (e.g. I421 / British Telecom) don't give us the
2226                                            channel number, so we have to figure it out...  This must be why
2227                                            everybody resets exactly a channel at a time. */
2228                                         for (x = 0; x < pri->numchans; x++) {
2229                                                 if (pri->pvts[x] && pri->pvts[x]->resetting) {
2230                                                         chanpos = x;
2231                                                         sig_pri_lock_private(pri->pvts[chanpos]);
2232                                                         ast_debug(1, "Assuming restart ack is really for channel %d/%d span %d\n", pri->pvts[chanpos]->logicalspan,
2233                                                                 pri->pvts[chanpos]->prioffset, pri->span);
2234                                                         if (pri->pvts[chanpos]->owner) {
2235                                                                 ast_log(LOG_WARNING, "Got restart ack on channel %d/%d with owner on span %d\n", pri->pvts[chanpos]->logicalspan,
2236                                                                         pri->pvts[chanpos]->prioffset, pri->span);
2237                                                                 ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2238                                                         }
2239                                                         pri->pvts[chanpos]->resetting = 0;
2240                                                         ast_verb(3, "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
2241                                                                 pri->pvts[chanpos]->prioffset, pri->span);
2242                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
2243                                                         if (pri->resetting)
2244                                                                 pri_check_restart(pri);
2245                                                         break;
2246                                                 }
2247                                         }
2248                                         if (chanpos < 0) {
2249                                                 ast_log(LOG_WARNING, "Restart ACK requested on strange channel %d/%d span %d\n",
2250                                                         PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
2251                                         }
2252                                 } else {
2253                                         if (pri->pvts[chanpos]) {
2254                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2255                                                 if (pri->pvts[chanpos]->owner) {
2256                                                         ast_log(LOG_WARNING, "Got restart ack on channel %d/%d span %d with owner\n",
2257                                                                 PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
2258                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2259                                                 }
2260                                                 pri->pvts[chanpos]->resetting = 0;
2261                                                 ast_verb(3, "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
2262                                                         pri->pvts[chanpos]->prioffset, pri->span);
2263                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2264                                                 if (pri->resetting)
2265                                                         pri_check_restart(pri);
2266                                         }
2267                                 }
2268                                 break;
2269                         case PRI_EVENT_SETUP_ACK:
2270                                 chanpos = pri_find_principle(pri, e->setup_ack.channel);
2271                                 if (chanpos < 0) {
2272                                         ast_log(LOG_WARNING, "Received SETUP_ACKNOWLEDGE on unconfigured channel %d/%d span %d\n",
2273                                                 PRI_SPAN(e->setup_ack.channel), PRI_CHANNEL(e->setup_ack.channel), pri->span);
2274                                 } else {
2275                                         chanpos = pri_fixup_principle(pri, chanpos, e->setup_ack.call);
2276                                         if (chanpos > -1) {
2277                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2278                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->setup_ack.channel,
2279                                                         e->setup_ack.subcmds);
2280                                                 pri->pvts[chanpos]->setup_ack = 1;
2281                                                 /* Send any queued digits */
2282                                                 for (x = 0;x < strlen(pri->pvts[chanpos]->dialdest); x++) {
2283                                                         ast_debug(1, "Sending pending digit '%c'\n", pri->pvts[chanpos]->dialdest[x]);
2284                                                         pri_information(pri->pri, pri->pvts[chanpos]->call,
2285                                                                 pri->pvts[chanpos]->dialdest[x]);
2286                                                 }
2287                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2288                                         } else
2289                                                 ast_log(LOG_WARNING, "Unable to move channel %d!\n", e->setup_ack.channel);
2290                                 }
2291                                 break;
2292                         case PRI_EVENT_NOTIFY:
2293                                 chanpos = pri_find_principle(pri, e->notify.channel);
2294                                 if (chanpos < 0) {
2295                                         ast_log(LOG_WARNING, "Received NOTIFY on unconfigured channel %d/%d span %d\n",
2296                                                 PRI_SPAN(e->notify.channel), PRI_CHANNEL(e->notify.channel), pri->span);
2297                                 } else {
2298                                         sig_pri_lock_private(pri->pvts[chanpos]);
2299                                         sig_pri_handle_subcmds(pri, chanpos, e->e, e->notify.channel,
2300                                                 e->notify.subcmds);
2301                                         switch (e->notify.info) {
2302                                         case PRI_NOTIFY_REMOTE_HOLD:
2303                                                 if (!pri->discardremoteholdretrieval) {
2304                                                         struct ast_frame f = { AST_FRAME_CONTROL, };
2305
2306                                                         f.subclass = AST_CONTROL_HOLD;
2307                                                         pri_queue_frame(pri->pvts[chanpos], &f, pri);
2308                                                 }
2309                                                 break;
2310                                         case PRI_NOTIFY_REMOTE_RETRIEVAL:
2311                                                 if (!pri->discardremoteholdretrieval) {
2312                                                         struct ast_frame f = { AST_FRAME_CONTROL, };
2313
2314                                                         f.subclass = AST_CONTROL_UNHOLD;
2315                                                         pri_queue_frame(pri->pvts[chanpos], &f, pri);
2316                                                 }
2317                                                 break;
2318                                         }
2319                                         sig_pri_unlock_private(pri->pvts[chanpos]);
2320                                 }
2321                                 break;
2322                         default:
2323                                 ast_debug(1, "Event: %d\n", e->e);
2324                         }
2325                 }
2326                 ast_mutex_unlock(&pri->lock);
2327         }
2328         /* Never reached */
2329         return NULL;
2330 }
2331
2332 void sig_pri_init_pri(struct sig_pri_pri *pri)
2333 {
2334         int i;
2335
2336         memset(pri, 0, sizeof(*pri));
2337
2338         ast_mutex_init(&pri->lock);
2339
2340         pri->master = AST_PTHREADT_NULL;
2341         for (i = 0; i < NUM_DCHANS; i++)
2342                 pri->fds[i] = -1;
2343 }
2344
2345 int sig_pri_hangup(struct sig_pri_chan *p, struct ast_channel *ast)
2346 {
2347         int res = 0;
2348 #ifdef SUPPORT_USERUSER
2349         const char *useruser = pbx_builtin_getvar_helper(ast, "USERUSERINFO");
2350 #endif
2351
2352         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
2353         if (!ast->tech_pvt) {
2354                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2355                 return 0;
2356         }
2357
2358         p->owner = NULL;
2359         p->outgoing = 0;
2360         p->digital = 0;
2361         p->proceeding = 0;
2362         p->progress = 0;
2363         p->alerting = 0;
2364         p->setup_ack = 0;
2365         p->exten[0] = '\0';
2366         sig_pri_set_dialing(p, 0);
2367
2368         if (!p->call) {
2369                 res = 0;
2370                 goto exit;
2371         }
2372
2373         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2374         if (!pri_grab(p, p->pri)) {
2375                 if (p->alreadyhungup) {
2376                         ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2377
2378 #ifdef SUPPORT_USERUSER
2379                         pri_call_set_useruser(p->call, useruser);
2380 #endif
2381
2382                         pri_hangup(p->pri->pri, p->call, -1);
2383                         p->call = NULL;
2384                 } else {
2385                         const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2386                         int icause = ast->hangupcause ? ast->hangupcause : -1;
2387                         ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2388
2389 #ifdef SUPPORT_USERUSER
2390                         pri_call_set_useruser(p->call, useruser);
2391 #endif
2392
2393                         p->alreadyhungup = 1;
2394                         if (cause) {
2395                                 if (atoi(cause))
2396                                         icause = atoi(cause);
2397                         }
2398                         pri_hangup(p->pri->pri, p->call, icause);
2399                 }
2400                 if (res < 0)
2401                         ast_log(LOG_WARNING, "pri_disconnect failed\n");
2402                 pri_rel(p->pri);
2403         } else {
2404                 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2405                 res = -1;
2406         }
2407
2408 exit:
2409         ast->tech_pvt = NULL;
2410         return res;
2411 }
2412
2413 int sig_pri_call(struct sig_pri_chan *p, struct ast_channel *ast, char *rdest, int timeout, int layer1)
2414 {
2415         char dest[256]; /* must be same length as p->dialdest */
2416         struct pri_sr *sr;
2417         char *c, *l, *n, *s = NULL;
2418 #ifdef SUPPORT_USERUSER
2419         const char *useruser;
2420 #endif
2421         int pridialplan;
2422         int dp_strip;
2423         int prilocaldialplan;
2424         int ldp_strip;
2425         int exclusive;
2426
2427         ast_log(LOG_DEBUG, "CALLING CID_NAME: %s CID_NUM:: %s\n", ast->cid.cid_name, ast->cid.cid_num);
2428
2429         if (!p->pri) {
2430                 ast_log(LOG_ERROR, "Could not find pri on channel %d\n", p->channel);
2431                 return -1;
2432         }
2433
2434
2435         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2436                 ast_log(LOG_WARNING, "sig_pri_call called on %s, neither down nor reserved\n", ast->name);
2437                 return -1;
2438         }
2439
2440         ast_copy_string(dest, rdest, sizeof(dest));
2441
2442         p->dialdest[0] = '\0';
2443         p->outgoing = 1;
2444
2445         c = strchr(dest, '/');
2446         if (c) {
2447                 c++;
2448         } else {
2449                 c = "";
2450         }
2451
2452         l = NULL;
2453         n = NULL;
2454         if (!p->hidecallerid) {
2455                 l = ast->connected.id.number;
2456                 if (!p->hidecalleridname) {
2457                         n = ast->connected.id.name;
2458                 }
2459         }
2460
2461         if (strlen(c) < p->stripmsd) {
2462                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2463                 return -1;
2464         }
2465         if (pri_grab(p, p->pri)) {
2466                 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2467                 return -1;
2468         }
2469         if (!(p->call = pri_new_call(p->pri->pri))) {
2470                 ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2471                 pri_rel(p->pri);
2472                 return -1;
2473         }
2474         if (!(sr = pri_sr_new())) {
2475                 ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2476                 pri_destroycall(p->pri->pri, p->call);
2477                 p->call = NULL;
2478                 pri_rel(p->pri);
2479                 return -1;
2480         }
2481
2482         p->digital = IS_DIGITAL(ast->transfercapability);
2483
2484         /* Should the picked channel be used exclusively? */
2485         if (p->priexclusive || p->pri->nodetype == PRI_NETWORK) {
2486                 exclusive = 1;
2487         } else {
2488                 exclusive = 0;
2489         }
2490
2491         pri_sr_set_channel(sr, PVT_TO_CHANNEL(p), exclusive, 1);
2492         pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability,
2493                 (p->digital ? -1 : layer1));
2494
2495         if (p->pri->facilityenable)
2496                 pri_facility_enable(p->pri->pri);
2497
2498         ast_verb(3, "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2499         dp_strip = 0;
2500         pridialplan = p->pri->dialplan - 1;
2501         if (pridialplan == -2 || pridialplan == -3) { /* compute dynamically */
2502                 if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2503                         if (pridialplan == -2) {
2504                                 dp_strip = strlen(p->pri->internationalprefix);
2505                         }
2506                         pridialplan = PRI_INTERNATIONAL_ISDN;
2507                 } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2508                         if (pridialplan == -2) {
2509                                 dp_strip = strlen(p->pri->nationalprefix);
2510                         }
2511                         pridialplan = PRI_NATIONAL_ISDN;
2512                 } else {
2513                         pridialplan = PRI_LOCAL_ISDN;
2514                 }
2515         }
2516         while (c[p->stripmsd] > '9' && c[p->stripmsd] != '*' && c[p->stripmsd] != '#') {
2517                 switch (c[p->stripmsd]) {
2518                 case 'U':
2519                         pridialplan = (PRI_TON_UNKNOWN << 4) | (pridialplan & 0xf);
2520                         break;
2521                 case 'I':
2522                         pridialplan = (PRI_TON_INTERNATIONAL << 4) | (pridialplan & 0xf);
2523                         break;
2524                 case 'N':
2525                         pridialplan = (PRI_TON_NATIONAL << 4) | (pridialplan & 0xf);
2526                         break;
2527                 case 'L':
2528                         pridialplan = (PRI_TON_NET_SPECIFIC << 4) | (pridialplan & 0xf);
2529                         break;
2530                 case 'S':
2531                         pridialplan = (PRI_TON_SUBSCRIBER << 4) | (pridialplan & 0xf);
2532                         break;
2533                 case 'V':
2534                         pridialplan = (PRI_TON_ABBREVIATED << 4) | (pridialplan & 0xf);
2535                         break;
2536                 case 'R':
2537                         pridialplan = (PRI_TON_RESERVED << 4) | (pridialplan & 0xf);
2538                         break;
2539                 case 'u':
2540                         pridialplan = PRI_NPI_UNKNOWN | (pridialplan & 0xf0);
2541                         break;
2542                 case 'e':
2543                         pridialplan = PRI_NPI_E163_E164 | (pridialplan & 0xf0);
2544                         break;
2545                 case 'x':
2546                         pridialplan = PRI_NPI_X121 | (pridialplan & 0xf0);
2547                         break;
2548                 case 'f':
2549                         pridialplan = PRI_NPI_F69 | (pridialplan & 0xf0);
2550                         break;
2551                 case 'n':
2552                         pridialplan = PRI_NPI_NATIONAL | (pridialplan & 0xf0);
2553                         break;
2554                 case 'p':
2555                         pridialplan = PRI_NPI_PRIVATE | (pridialplan & 0xf0);
2556                         break;
2557                 case 'r':
2558                         pridialplan = PRI_NPI_RESERVED | (pridialplan & 0xf0);
2559                         break;
2560 #if defined(HAVE_PRI_REVERSE_CHARGE)
2561                 case 'C':
2562                         pri_sr_set_reversecharge(sr, PRI_REVERSECHARGE_REQUESTED);
2563                         break;
2564 #endif
2565                 default:
2566                         if (isalpha(c[p->stripmsd])) {
2567                                 ast_log(LOG_WARNING, "Unrecognized pridialplan %s modifier: %c\n",
2568                                         c[p->stripmsd] > 'Z' ? "NPI" : "TON", c[p->stripmsd]);
2569                         }
2570                         break;
2571                 }
2572                 c++;
2573         }
2574         pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2575
2576         ldp_strip = 0;
2577         prilocaldialplan = p->pri->localdialplan - 1;
2578         if ((l != NULL) && (prilocaldialplan == -2 || prilocaldialplan == -3)) { /* compute dynamically */
2579                 if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2580                         if (prilocaldialplan == -2) {
2581                                 ldp_strip = strlen(p->pri->internationalprefix);
2582                         }
2583                         prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2584                 } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2585                         if (prilocaldialplan == -2) {
2586                                 ldp_strip = strlen(p->pri->nationalprefix);
2587                         }
2588                         prilocaldialplan = PRI_NATIONAL_ISDN;
2589                 } else {
2590                         prilocaldialplan = PRI_LOCAL_ISDN;
2591                 }
2592         }
2593         if (l != NULL) {
2594                 while (*l > '9' && *l != '*' && *l != '#') {
2595                         switch (*l) {
2596                         case 'U':
2597                                 prilocaldialplan = (PRI_TON_UNKNOWN << 4) | (prilocaldialplan & 0xf);
2598                                 break;
2599                         case 'I':
2600                                 prilocaldialplan = (PRI_TON_INTERNATIONAL << 4) | (prilocaldialplan & 0xf);
2601                                 break;
2602                         case 'N':
2603                                 prilocaldialplan = (PRI_TON_NATIONAL << 4) | (prilocaldialplan & 0xf);
2604                                 break;
2605                         case 'L':
2606                                 prilocaldialplan = (PRI_TON_NET_SPECIFIC << 4) | (prilocaldialplan & 0xf);
2607                                 break;
2608                         case 'S':
2609                                 prilocaldialplan = (PRI_TON_SUBSCRIBER << 4) | (prilocaldialplan & 0xf);
2610                                 break;
2611                         case 'V':
2612                                 prilocaldialplan = (PRI_TON_ABBREVIATED << 4) | (prilocaldialplan & 0xf);
2613                                 break;
2614                         case 'R':
2615                                 prilocaldialplan = (PRI_TON_RESERVED << 4) | (prilocaldialplan & 0xf);
2616                                 break;
2617                         case 'u':
2618                                 prilocaldialplan = PRI_NPI_UNKNOWN | (prilocaldialplan & 0xf0);
2619                                 break;
2620                         case 'e':
2621                                 prilocaldialplan = PRI_NPI_E163_E164 | (prilocaldialplan & 0xf0);
2622                                 break;
2623                         case 'x':
2624                                 prilocaldialplan = PRI_NPI_X121 | (prilocaldialplan & 0xf0);
2625                                 break;
2626                         case 'f':
2627                                 prilocaldialplan = PRI_NPI_F69 | (prilocaldialplan & 0xf0);
2628                                 break;
2629                         case 'n':
2630                                 prilocaldialplan = PRI_NPI_NATIONAL | (prilocaldialplan & 0xf0);
2631                                 break;
2632                         case 'p':
2633                                 prilocaldialplan = PRI_NPI_PRIVATE | (prilocaldialplan & 0xf0);
2634                                 break;
2635                         case 'r':
2636                                 prilocaldialplan = PRI_NPI_RESERVED | (prilocaldialplan & 0xf0);
2637                                 break;
2638                         default:
2639                                 if (isalpha(*l)) {
2640                                         ast_log(LOG_WARNING,
2641                                                 "Unrecognized prilocaldialplan %s modifier: %c\n",
2642                                                 *l > 'Z' ? "NPI" : "TON", *l);
2643                                 }
2644                                 break;
2645                         }
2646                         l++;
2647                 }
2648         }
2649         pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2650                 p->use_callingpres ? ast->connected.id.number_presentation : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2651         sig_pri_redirecting_update(p, ast);
2652
2653 #ifdef SUPPORT_USERUSER
2654         /* User-user info */
2655         useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2656         if (useruser)
2657                 pri_sr_set_useruser(sr, useruser);
2658 #endif
2659
2660         if (pri_setup(p->pri->pri, p->call, sr)) {
2661                 ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n",
2662                         c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2663                 pri_rel(p->pri);
2664                 pri_sr_free(sr);
2665                 return -1;
2666         }
2667         pri_sr_free(sr);
2668         ast_setstate(ast, AST_STATE_DIALING);
2669         sig_pri_set_dialing(p, 1);
2670         pri_rel(p->pri);
2671         return 0;
2672 }
2673
2674 int sig_pri_indicate(struct sig_pri_chan *p, struct ast_channel *chan, int condition, const void *data, size_t datalen)
2675 {
2676         int res = -1;
2677
2678         switch (condition) {
2679         case AST_CONTROL_BUSY:
2680                 if (p->priindication_oob) {
2681                         chan->hangupcause = AST_CAUSE_USER_BUSY;
2682                         chan->_softhangup |= AST_SOFTHANGUP_DEV;
2683                         res = 0;
2684                 } else if (!p->progress && p->pri && !p->outgoing) {
2685                         if (p->pri->pri) {
2686                                 if (!pri_grab(p, p->pri)) {
2687 #ifdef HAVE_PRI_PROG_W_CAUSE
2688                                         pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, PRI_CAUSE_USER_BUSY); /* cause = 17 */
2689 #else
2690                                         pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
2691 #endif
2692                                         pri_rel(p->pri);
2693                                 } else {
2694                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2695                                 }
2696                         }
2697                         p->progress = 1;
2698                         res = sig_pri_play_tone(p, SIG_PRI_TONE_BUSY);
2699                 }
2700                 break;
2701         case AST_CONTROL_RINGING:
2702                 if ((!p->alerting) && p->pri && !p->outgoing && (chan->_state != AST_STATE_UP)) {
2703                         if (p->pri->pri) {
2704                                 if (!pri_grab(p, p->pri)) {
2705                                         pri_acknowledge(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
2706                                         pri_rel(p->pri);
2707                                 } else {
2708                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2709                                 }
2710                         }
2711                         p->alerting = 1;
2712                 }
2713                 res = sig_pri_play_tone(p, SIG_PRI_TONE_RINGTONE);
2714                 if (chan->_state != AST_STATE_UP) {
2715                         if (chan->_state != AST_STATE_RING)
2716                                 ast_setstate(chan, AST_STATE_RINGING);
2717                 }
2718                 break;
2719         case AST_CONTROL_PROCEEDING:
2720                 ast_debug(1,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
2721                 if (!p->proceeding && p->pri && !p->outgoing) {
2722                         if (p->pri->pri) {
2723                                 if (!pri_grab(p, p->pri)) {
2724                                         pri_proceeding(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
2725                                         pri_rel(p->pri);
2726                                 } else {
2727                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2728                                 }
2729                         }
2730                         p->proceeding = 1;
2731                         sig_pri_set_dialing(p, 0);
2732                 }
2733                 /* don't continue in ast_indicate */
2734                 res = 0;
2735                 break;
2736         case AST_CONTROL_PROGRESS:
2737                 ast_debug(1,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
2738                 p->digital = 0; /* Digital-only calls isn't allowing any inband progress messages */
2739                 if (!p->progress && p->pri && !p->outgoing) {
2740                         if (p->pri->pri) {
2741                                 if (!pri_grab(p, p->pri)) {
2742 #ifdef HAVE_PRI_PROG_W_CAUSE
2743                                         pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, -1);  /* no cause at all */
2744 #else
2745                                         pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
2746 #endif
2747                                         pri_rel(p->pri);
2748                                 } else {
2749                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2750                                 }
2751                         }
2752                         p->progress = 1;
2753                 }
2754                 /* don't continue in ast_indicate */
2755                 res = 0;
2756                 break;
2757         case AST_CONTROL_CONGESTION:
2758                 chan->hangupcause = AST_CAUSE_CONGESTION;
2759                 if (p->priindication_oob) {
2760                         chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
2761                         chan->_softhangup |= AST_SOFTHANGUP_DEV;
2762                         res = 0;
2763                 } else if (!p->progress && p->pri && !p->outgoing) {
2764                         if (p->pri) {
2765                                 if (!pri_grab(p, p->pri)) {
2766 #ifdef HAVE_PRI_PROG_W_CAUSE
2767                                         pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, PRI_CAUSE_SWITCH_CONGESTION); /* cause = 42 */
2768 #else
2769                                         pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
2770 #endif
2771                                         pri_rel(p->pri);
2772                                 } else {
2773                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2774                                 }
2775                         }
2776                         p->progress = 1;
2777                         res = sig_pri_play_tone(p, SIG_PRI_TONE_CONGESTION);
2778                 }
2779                 break;
2780         case AST_CONTROL_HOLD:
2781                 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
2782                         if (!pri_grab(p, p->pri)) {
2783                                 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_HOLD);
2784                                 pri_rel(p->pri);
2785                         } else {
2786                                 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2787                         }
2788                 } else
2789                         ast_moh_start(chan, data, p->mohinterpret);
2790                 break;
2791         case AST_CONTROL_UNHOLD:
2792                 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
2793                         if (!pri_grab(p, p->pri)) {
2794                                 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_RETRIEVAL);
2795                                 pri_rel(p->pri);
2796                         }
2797                 } else
2798                         ast_moh_stop(chan);
2799                 break;
2800         case AST_CONTROL_SRCUPDATE:
2801                 res = 0;
2802                 break;
2803         case -1:
2804                 res = sig_pri_play_tone(p, -1);
2805                 break;
2806         case AST_CONTROL_CONNECTED_LINE:
2807                 ast_debug(1, "Received AST_CONTROL_CONNECTED_LINE on %s\n", chan->name);
2808                 if (p->pri && !pri_grab(p, p->pri)) {
2809                         struct pri_party_connected_line connected;
2810
2811                         memset(&connected, 0, sizeof(connected));
2812                         sig_pri_party_id_from_ast(&connected.id, &chan->connected.id);
2813
2814                         pri_connected_line_update(p->pri->pri, p->call, &connected);
2815                         pri_rel(p->pri);
2816                 }
2817                 break;
2818         case AST_CONTROL_REDIRECTING:
2819                 ast_debug(1, "Received AST_CONTROL_REDIRECTING on %s\n", chan->name);
2820                 if (p->pri && !pri_grab(p, p->pri)) {
2821                         sig_pri_redirecting_update(p, chan);
2822                         pri_rel(p->pri);
2823                 }
2824                 break;
2825         }
2826
2827         return res;
2828 }
2829
2830 int sig_pri_answer(struct sig_pri_chan *p, struct ast_channel *ast)
2831 {
2832         int res = 0;
2833         /* Send a pri acknowledge */
2834         if (!pri_grab(p, p->pri)) {
2835                 p->proceeding = 1;
2836                 sig_pri_set_dialing(p, 0);
2837                 res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2838                 pri_rel(p->pri);
2839         } else {
2840                 res = -1;
2841         }
2842         ast_setstate(ast, AST_STATE_UP);
2843         return res;
2844 }
2845
2846 int sig_pri_available(struct sig_pri_chan *p, int channelmatch, ast_group_t groupmatch, int *reason, int *channelmatched, int *groupmatched)
2847 {
2848         /* If no owner definitely available */
2849         if (!p->owner) {
2850                 /* Trust PRI */
2851                 if (p->pri) {
2852 #ifdef HAVE_PRI_SERVICE_MESSAGES
2853                         char db_chan_name[20], db_answer[5], state;
2854                         int why = 0;
2855
2856                         snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, p->pri->span, p->channel);
2857                         if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, siz