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