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