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