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