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