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