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