Sanity adjustments to pri_ss_thread for sig_pri environment.
[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         if (!chan) {
605                 /* We lost the owner before we could get started. */
606                 return NULL;
607         }
608
609         /*
610          * In the bizarre case where the channel has become a zombie before we
611          * even get started here, abort safely.
612          */
613         if (!chan->tech_pvt) {
614                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
615                 ast_hangup(chan);
616                 return NULL;
617         }
618
619         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
620
621         /* Now loop looking for an extension */
622         ast_copy_string(exten, p->exten, sizeof(exten));
623         len = strlen(exten);
624         res = 0;
625         while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
626                 if (len && !ast_ignore_pattern(chan->context, exten))
627                         sig_pri_play_tone(p, -1);
628                 else
629                         sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
630                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
631                         timeout = pri_matchdigittimeout;
632                 else
633                         timeout = pri_gendigittimeout;
634                 res = ast_waitfordigit(chan, timeout);
635                 if (res < 0) {
636                         ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
637                         ast_hangup(chan);
638                         return NULL;
639                 } else if (res) {
640                         exten[len++] = res;
641                         exten[len] = '\0';
642                 } else
643                         goto exit;
644         }
645         /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
646         if (ast_strlen_zero(exten)) {
647                 ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
648                 exten[0] = 's';
649                 exten[1] = '\0';
650         }
651         sig_pri_play_tone(p, -1);
652         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
653                 /* Start the real PBX */
654                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
655                 sig_pri_set_echocanceller(p, 1);
656                 ast_setstate(chan, AST_STATE_RING);
657                 res = ast_pbx_run(chan);
658                 if (res) {
659                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
660                 }
661         } else {
662                 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
663                 chan->hangupcause = AST_CAUSE_UNALLOCATED;
664                 ast_hangup(chan);
665                 p->exten[0] = '\0';
666                 /* Since we send release complete here, we won't get one */
667                 p->call = NULL;
668         }
669         return NULL;
670
671 exit:
672         res = sig_pri_play_tone(p, SIG_PRI_TONE_CONGESTION);
673         if (res < 0)
674                 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
675         ast_hangup(chan);
676         return NULL;
677 }
678
679 void pri_event_alarm(struct sig_pri_pri *pri, int index, int before_start_pri)
680 {
681         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
682         if (!before_start_pri)
683                 pri_find_dchan(pri);
684 }
685
686 void pri_event_noalarm(struct sig_pri_pri *pri, int index, int before_start_pri)
687 {
688         pri->dchanavail[index] |= DCHAN_NOTINALARM;
689         if (!before_start_pri)
690                 pri_restart(pri->dchans[index]);
691 }
692
693 #if defined(SUPPORT_USERUSER)
694 /*!
695  * \internal
696  * \brief Obtain the sig_pri owner channel lock if the owner exists.
697  * \since 1.6.3
698  *
699  * \param pri sig_pri PRI control structure.
700  * \param chanpos Channel position in the span.
701  *
702  * \note Assumes the pri->lock is already obtained.
703  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
704  *
705  * \return Nothing
706  */
707 static void sig_pri_lock_owner(struct sig_pri_pri *pri, int chanpos)
708 {
709         for (;;) {
710                 if (!pri->pvts[chanpos]->owner) {
711                         /* There is no owner lock to get. */
712                         break;
713                 }
714                 if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
715                         /* We got the lock */
716                         break;
717                 }
718                 /* We must unlock the PRI to avoid the possibility of a deadlock */
719                 ast_mutex_unlock(&pri->lock);
720                 PRI_DEADLOCK_AVOIDANCE(pri->pvts[chanpos]);
721                 ast_mutex_lock(&pri->lock);
722         }
723 }
724 #endif  /* defined(SUPPORT_USERUSER) */
725
726 static void *pri_dchannel(void *vpri)
727 {
728         struct sig_pri_pri *pri = vpri;
729         pri_event *e;
730         struct pollfd fds[NUM_DCHANS];
731         int res;
732         int chanpos = 0;
733         int x;
734         struct ast_channel *c;
735         struct timeval tv, lowest, *next;
736         int doidling=0;
737         char *cc;
738         time_t t;
739         int i, which=-1;
740         int numdchans;
741         pthread_t threadid;
742         char ani2str[6];
743         char plancallingnum[AST_MAX_EXTENSION];
744         char plancallingani[AST_MAX_EXTENSION];
745         char calledtonstr[10];
746         struct timeval lastidle = { 0, 0 };
747         pthread_t p;
748         struct ast_channel *idle;
749         char idlen[80];
750         int nextidle = -1;
751         int haveidles;
752         int activeidles;
753
754         gettimeofday(&lastidle, NULL);
755         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
756
757         if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
758                 /* Need to do idle dialing, check to be sure though */
759                 cc = strchr(pri->idleext, '@');
760                 if (cc) {
761                         *cc = '\0';
762                         cc++;
763                         ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
764 #if 0
765                         /* Extensions may not be loaded yet */
766                         if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
767                                 ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
768                         else
769 #endif
770                                 doidling = 1;
771                 } else
772                         ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
773         }
774         for (;;) {
775                 for (i = 0; i < NUM_DCHANS; i++) {
776                         if (!pri->dchans[i])
777                                 break;
778                         fds[i].fd = pri->fds[i];
779                         fds[i].events = POLLIN | POLLPRI;
780                         fds[i].revents = 0;
781                 }
782                 numdchans = i;
783                 time(&t);
784                 ast_mutex_lock(&pri->lock);
785                 if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->sig != SIG_BRI_PTMP) && (pri->resetinterval > 0)) {
786                         if (pri->resetting && pri_is_up(pri)) {
787                                 if (pri->resetpos < 0)
788                                         pri_check_restart(pri);
789                         } else {
790                                 if (!pri->resetting     && (t - pri->lastreset) >= pri->resetinterval) {
791                                         pri->resetting = 1;
792                                         pri->resetpos = -1;
793                                 }
794                         }
795                 }
796                 /* Look for any idle channels if appropriate */
797                 if (doidling && pri_is_up(pri)) {
798                         nextidle = -1;
799                         haveidles = 0;
800                         activeidles = 0;
801                         for (x = pri->numchans; x >= 0; x--) {
802                                 if (pri->pvts[x] && !pri->pvts[x]->owner &&
803                                         !pri->pvts[x]->call) {
804                                         if (haveidles < pri->minunused) {
805                                                 haveidles++;
806                                         } else if (!pri->pvts[x]->resetting) {
807                                                 nextidle = x;
808                                                 break;
809                                         }
810                                 } else if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall)
811                                         activeidles++;
812                         }
813                         if (nextidle > -1) {
814                                 if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
815                                         /* Don't create a new idle call more than once per second */
816                                         snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
817                                         idle = sig_pri_request(pri->pvts[nextidle], AST_FORMAT_ULAW, NULL);
818                                         if (idle) {
819                                                 pri->pvts[nextidle]->isidlecall = 1;
820                                                 if (ast_pthread_create_background(&p, NULL, do_idle_thread, idle)) {
821                                                         ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
822                                                         ast_hangup(idle);
823                                                 }
824                                         } else
825                                                 ast_log(LOG_WARNING, "Unable to request channel 'DAHDI/%s' for idle call\n", idlen);
826                                         gettimeofday(&lastidle, NULL);
827                                 }
828                         } else if ((haveidles < pri->minunused) &&
829                                 (activeidles > pri->minidle)) {
830                                 /* Mark something for hangup if there is something
831                                    that can be hungup */
832                                 for (x = pri->numchans; x >= 0; x--) {
833                                         /* find a candidate channel */
834                                         if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
835                                                 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
836                                                 haveidles++;
837                                                 /* Stop if we have enough idle channels or
838                                                   can't spare any more active idle ones */
839                                                 if ((haveidles >= pri->minunused) ||
840                                                         (activeidles <= pri->minidle))
841                                                         break;
842                                         }
843                                 }
844                         }
845                 }
846                 /* Start with reasonable max */
847                 lowest = ast_tv(60, 0);
848                 for (i = 0; i < NUM_DCHANS; i++) {
849                         /* Find lowest available d-channel */
850                         if (!pri->dchans[i])
851                                 break;
852                         if ((next = pri_schedule_next(pri->dchans[i]))) {
853                                 /* We need relative time here */
854                                 tv = ast_tvsub(*next, ast_tvnow());
855                                 if (tv.tv_sec < 0) {
856                                         tv = ast_tv(0,0);
857                                 }
858                                 if (doidling || pri->resetting) {
859                                         if (tv.tv_sec > 1) {
860                                                 tv = ast_tv(1, 0);
861                                         }
862                                 } else {
863                                         if (tv.tv_sec > 60) {
864                                                 tv = ast_tv(60, 0);
865                                         }
866                                 }
867                         } else if (doidling || pri->resetting) {
868                                 /* Make sure we stop at least once per second if we're
869                                    monitoring idle channels */
870                                 tv = ast_tv(1,0);
871                         } else {
872                                 /* Don't poll for more than 60 seconds */
873                                 tv = ast_tv(60, 0);
874                         }
875                         if (!i || ast_tvcmp(tv, lowest) < 0) {
876                                 lowest = tv;
877                         }
878                 }
879                 ast_mutex_unlock(&pri->lock);
880
881                 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
882                 pthread_testcancel();
883                 e = NULL;
884                 res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
885                 pthread_testcancel();
886                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
887
888                 ast_mutex_lock(&pri->lock);
889                 if (!res) {
890                         for (which = 0; which < NUM_DCHANS; which++) {
891                                 if (!pri->dchans[which])
892                                         break;
893                                 /* Just a timeout, run the scheduler */
894                                 e = pri_schedule_run(pri->dchans[which]);
895                                 if (e)
896                                         break;
897                         }
898                 } else if (res > -1) {
899                         for (which = 0; which < NUM_DCHANS; which++) {
900                                 if (!pri->dchans[which])
901                                         break;
902                                 if (fds[which].revents & POLLPRI) {
903                                         sig_pri_handle_dchan_exception(pri, which);
904                                 } else if (fds[which].revents & POLLIN) {
905                                         e = pri_check_event(pri->dchans[which]);
906                                 }
907                                 if (e)
908                                         break;
909                         }
910                 } else if (errno != EINTR)
911                         ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
912
913                 if (e) {
914                         if (pri->debug)
915                                 pri_dump_event(pri->dchans[which], e);
916
917                         if (e->e != PRI_EVENT_DCHAN_DOWN) {
918                                 if (!(pri->dchanavail[which] & DCHAN_UP)) {
919                                         ast_verb(2, "%s D-Channel on span %d up\n", pri_order(which), pri->span);
920                                 }
921                                 pri->dchanavail[which] |= DCHAN_UP;
922                         } else {
923                                 if (pri->dchanavail[which] & DCHAN_UP) {
924                                         ast_verb(2, "%s D-Channel on span %d down\n", pri_order(which), pri->span);
925                                 }
926                                 pri->dchanavail[which] &= ~DCHAN_UP;
927                         }
928
929                         if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
930                                 /* Must be an NFAS group that has the secondary dchan active */
931                                 pri->pri = pri->dchans[which];
932
933                         switch (e->e) {
934                         case PRI_EVENT_DCHAN_UP:
935                                 if (!pri->pri) pri_find_dchan(pri);
936
937                                 /* Note presense of D-channel */
938                                 time(&pri->lastreset);
939
940                                 /* Restart in 5 seconds */
941                                 if (pri->resetinterval > -1) {
942                                         pri->lastreset -= pri->resetinterval;
943                                         pri->lastreset += 5;
944                                 }
945                                 pri->resetting = 0;
946                                 /* Take the channels from inalarm condition */
947                                 for (i = 0; i < pri->numchans; i++)
948                                         if (pri->pvts[i]) {
949                                                 pri->pvts[i]->inalarm = 0;
950                                         }
951                                 break;
952                         case PRI_EVENT_DCHAN_DOWN:
953                                 pri_find_dchan(pri);
954                                 if (!pri_is_up(pri)) {
955                                         pri->resetting = 0;
956                                         /* Hangup active channels and put them in alarm mode */
957                                         for (i = 0; i < pri->numchans; i++) {
958                                                 struct sig_pri_chan *p = pri->pvts[i];
959                                                 if (p) {
960                                                         if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
961                                                                 /* T309 is not enabled : hangup calls when alarm occurs */
962                                                                 if (p->call) {
963                                                                         if (p->pri && p->pri->pri) {
964                                                                                 pri_hangup(p->pri->pri, p->call, -1);
965                                                                                 pri_destroycall(p->pri->pri, p->call);
966                                                                                 p->call = NULL;
967                                                                         } else
968                                                                                 ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
969                                                                 }
970                                                                 if (p->owner)
971                                                                         ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
972                                                         }
973                                                         /* For PTMP connections with non persistent layer 2 we want
974                                                          * to *not* declare inalarm unless there actually is an alarm */
975                                                         if (p->pri->sig != SIG_BRI_PTMP) {
976                                                                 p->inalarm = 1;
977                                                         }
978                                                 }
979                                         }
980                                 }
981                                 break;
982                         case PRI_EVENT_RESTART:
983                                 if (e->restart.channel > -1) {
984                                         chanpos = pri_find_principle(pri, e->restart.channel);
985                                         if (chanpos < 0)
986                                                 ast_log(LOG_WARNING, "Restart requested on odd/unavailable channel number %d/%d on span %d\n",
987                                                         PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
988                                         else {
989 #ifdef HAVE_PRI_SERVICE_MESSAGES
990                                                 char db_chan_name[20], db_answer[5], state;
991                                                 int why, skipit = 0;
992
993                                                 ast_mutex_lock(&pri->pvts[chanpos]->service_lock);
994                                                 snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->pvts[chanpos]->pri->span, pri->pvts[chanpos]->channel);
995                                                 ast_mutex_unlock(&pri->pvts[chanpos]->service_lock);
996
997                                                 if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
998                                                         sscanf(db_answer, "%c:%d", &state, &why);
999                                                         if (why) {
1000                                                                 ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), ignoring RESTART\n", pri->span,
1001                                                                         e->restart.channel, (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
1002                                                                 skipit = 1;
1003                                                         } else {
1004                                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
1005                                                         }
1006                                                 }
1007                                                 if (!skipit) {
1008 #endif
1009                                                         ast_verb(3, "B-channel %d/%d restarted on span %d\n",
1010                                                                 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
1011                                                         sig_pri_lock_private(pri->pvts[chanpos]);
1012                                                         if (pri->pvts[chanpos]->call) {
1013                                                                 pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
1014                                                                 pri->pvts[chanpos]->call = NULL;
1015                                                         }
1016 #ifdef HAVE_PRI_SERVICE_MESSAGES
1017                                                 }
1018 #endif
1019                                                 /* Force soft hangup if appropriate */
1020                                                 if (pri->pvts[chanpos]->owner)
1021                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
1022                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1023                                         }
1024                                 } else {
1025                                         ast_verb(3, "Restart on requested on entire span %d\n", pri->span);
1026                                         for (x = 0; x < pri->numchans; x++)
1027                                                 if (pri->pvts[x]) {
1028                                                         sig_pri_lock_private(pri->pvts[x]);
1029                                                         if (pri->pvts[x]->call) {
1030                                                                 pri_destroycall(pri->pri, pri->pvts[x]->call);
1031                                                                 pri->pvts[x]->call = NULL;
1032                                                         }
1033                                                         if (pri->pvts[x]->owner)
1034                                                                 ast_softhangup_nolock(pri->pvts[x]->owner, AST_SOFTHANGUP_DEV);
1035                                                         sig_pri_unlock_private(pri->pvts[x]);
1036                                                 }
1037                                 }
1038                                 break;
1039                         case PRI_EVENT_KEYPAD_DIGIT:
1040                                 chanpos = pri_find_principle(pri, e->digit.channel);
1041                                 if (chanpos < 0) {
1042                                         ast_log(LOG_WARNING, "KEYPAD_DIGITs received on unconfigured channel %d/%d span %d\n",
1043                                                 PRI_SPAN(e->digit.channel), PRI_CHANNEL(e->digit.channel), pri->span);
1044                                 } else {
1045                                         chanpos = pri_fixup_principle(pri, chanpos, e->digit.call);
1046                                         if (chanpos > -1) {
1047                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1048                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
1049                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
1050                                                         && pri->pvts[chanpos]->call == e->digit.call
1051                                                         && pri->pvts[chanpos]->owner) {
1052                                                         /* how to do that */
1053                                                         int digitlen = strlen(e->digit.digits);
1054                                                         int i;
1055
1056                                                         for (i = 0; i < digitlen; i++) {
1057                                                                 struct ast_frame f = { AST_FRAME_DTMF, e->digit.digits[i], };
1058
1059                                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1060                                                         }
1061                                                 }
1062                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1063                                         }
1064                                 }
1065                                 break;
1066
1067                         case PRI_EVENT_INFO_RECEIVED:
1068                                 chanpos = pri_find_principle(pri, e->ring.channel);
1069                                 if (chanpos < 0) {
1070                                         ast_log(LOG_WARNING, "INFO received on unconfigured channel %d/%d span %d\n",
1071                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
1072                                 } else {
1073                                         chanpos = pri_fixup_principle(pri, chanpos, e->ring.call);
1074                                         if (chanpos > -1) {
1075                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1076                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
1077                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
1078                                                         && pri->pvts[chanpos]->call == e->ring.call
1079                                                         && pri->pvts[chanpos]->owner) {
1080                                                         /* how to do that */
1081                                                         int digitlen = strlen(e->ring.callednum);
1082                                                         int i;
1083
1084                                                         for (i = 0; i < digitlen; i++) {
1085                                                                 struct ast_frame f = { AST_FRAME_DTMF, e->ring.callednum[i], };
1086
1087                                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1088                                                         }
1089                                                 }
1090                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1091                                         }
1092                                 }
1093                                 break;
1094 #ifdef HAVE_PRI_SERVICE_MESSAGES
1095                         case PRI_EVENT_SERVICE:
1096                                 chanpos = pri_find_principle(pri, e->service.channel);
1097                                 if (chanpos < 0) {
1098                                         ast_log(LOG_WARNING, "Received service change status %d on unconfigured channel %d/%d span %d\n",
1099                                                 e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
1100                                 } else {
1101                                         char db_chan_name[20], db_answer[5], state;
1102                                         int ch, why = -1;
1103
1104                                         ast_mutex_lock(&pri->pvts[chanpos]->service_lock);
1105                                         ch = pri->pvts[chanpos]->channel;
1106                                         ast_mutex_unlock(&pri->pvts[chanpos]->service_lock);
1107
1108                                         snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->pvts[chanpos]->pri->span, ch);
1109                                         if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
1110                                                 sscanf(db_answer, "%c:%d", &state, &why);
1111                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
1112                                         }
1113                                         switch (e->service.changestatus) {
1114                                         case 0: /* in-service */
1115                                                 if (why > -1) {
1116                                                         if (why & SRVST_NEAREND) {
1117                                                                 snprintf(db_answer, sizeof(db_answer), "%s:%d", SRVST_TYPE_OOS, SRVST_NEAREND);
1118                                                                 ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
1119                                                                 ast_debug(2, "channel '%d' service state { near: out-of-service,  far: in-service }\n", ch);
1120                                                         }
1121                                                 }
1122                                                 break;
1123                                         case 2: /* out-of-service */
1124                                                 if (why == -1) {
1125                                                         why = SRVST_FAREND;
1126                                                 } else {
1127                                                         why |= SRVST_FAREND;
1128                                                 }
1129                                                 snprintf(db_answer, sizeof(db_answer), "%s:%d", SRVST_TYPE_OOS, why);
1130                                                 ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
1131                                                 break;
1132                                         default:
1133                                                 ast_log(LOG_ERROR, "Huh?  changestatus is: %d\n", e->service.changestatus);
1134                                         }
1135                                         ast_log(LOG_NOTICE, "Channel %d/%d span %d (logical: %d) received a change of service message, status '%d'\n",
1136                                                 PRI_SPAN(e->service.channel), PRI_CHANNEL(e->service.channel), pri->span, ch, e->service.changestatus);
1137                                 }
1138                                 break;
1139                         case PRI_EVENT_SERVICE_ACK:
1140                                 chanpos = pri_find_principle(pri, e->service_ack.channel);
1141                                 if (chanpos < 0) {
1142                                         ast_log(LOG_WARNING, "Received service acknowledge change status '%d' on unconfigured channel %d/%d span %d\n",
1143                                                 e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
1144                                 } else {
1145                                         ast_debug(2, "Channel %d/%d span %d received a change os service acknowledgement message, status '%d'\n",
1146                                                 PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span, e->service_ack.changestatus);
1147                                 }
1148                                 break;
1149 #endif
1150                         case PRI_EVENT_RING:
1151                                 if (e->ring.channel == -1)
1152                                         chanpos = pri_find_empty_chan(pri, 1);
1153                                 else
1154                                         chanpos = pri_find_principle(pri, e->ring.channel);
1155                                 /* if no channel specified find one empty */
1156                                 if (chanpos < 0) {
1157                                         ast_log(LOG_WARNING, "Ring requested on unconfigured channel %d/%d span %d\n",
1158                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
1159                                 } else {
1160                                         sig_pri_lock_private(pri->pvts[chanpos]);
1161                                         if (pri->pvts[chanpos]->owner) {
1162                                                 if (pri->pvts[chanpos]->call == e->ring.call) {
1163                                                         ast_log(LOG_WARNING, "Duplicate setup requested on channel %d/%d already in use on span %d\n",
1164                                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
1165                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1166                                                         break;
1167                                                 } else {
1168                                                         /* This is where we handle initial glare */
1169                                                         ast_debug(1, "Ring requested on channel %d/%d already in use or previously requested on span %d.  Attempting to renegotiating channel.\n",
1170                                                         PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
1171                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1172                                                         chanpos = -1;
1173                                                 }
1174                                         }
1175                                         if (chanpos > -1)
1176                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1177                                 }
1178                                 if ((chanpos < 0) && (e->ring.flexible))
1179                                         chanpos = pri_find_empty_chan(pri, 1);
1180                                 if (chanpos > -1) {
1181                                         sig_pri_lock_private(pri->pvts[chanpos]);
1182                                         pri->pvts[chanpos]->call = e->ring.call;
1183
1184                                         /* Use plancallingnum as a scratch buffer since it is initialized next. */
1185                                         apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri,
1186                                                 e->ring.redirectingnum, e->ring.callingplanrdnis);
1187                                         sig_pri_set_rdnis(pri->pvts[chanpos], plancallingnum);
1188
1189                                         /* Setup caller-id info */
1190                                         apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri, e->ring.callingnum, e->ring.callingplan);
1191                                         pri->pvts[chanpos]->cid_ani2 = 0;
1192                                         if (pri->pvts[chanpos]->use_callerid) {
1193                                                 ast_shrink_phone_number(plancallingnum);
1194                                                 ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
1195 #ifdef PRI_ANI
1196                                                 if (!ast_strlen_zero(e->ring.callingani)) {
1197                                                         apply_plan_to_number(plancallingani, sizeof(plancallingani), pri, e->ring.callingani, e->ring.callingplanani);
1198                                                         ast_shrink_phone_number(plancallingani);
1199                                                         ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani, sizeof(pri->pvts[chanpos]->cid_ani));
1200                                                 } else {
1201                                                         pri->pvts[chanpos]->cid_ani[0] = '\0';
1202                                                 }
1203 #endif
1204                                                 ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
1205                                                 pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
1206                                                 pri->pvts[chanpos]->callingpres = e->ring.callingpres;
1207                                                 if (e->ring.ani2 >= 0) {
1208                                                         pri->pvts[chanpos]->cid_ani2 = e->ring.ani2;
1209                                                 }
1210                                         } else {
1211                                                 pri->pvts[chanpos]->cid_num[0] = '\0';
1212                                                 pri->pvts[chanpos]->cid_ani[0] = '\0';
1213                                                 pri->pvts[chanpos]->cid_name[0] = '\0';
1214                                                 pri->pvts[chanpos]->cid_ton = 0;
1215                                                 pri->pvts[chanpos]->callingpres = 0;
1216                                         }
1217                                         sig_pri_set_caller_id(pri->pvts[chanpos]);
1218
1219                                         /* Set DNID on all incoming calls -- even immediate */
1220                                         sig_pri_set_dnid(pri->pvts[chanpos], e->ring.callednum);
1221
1222                                         /* If immediate=yes go to s|1 */
1223                                         if (pri->pvts[chanpos]->immediate) {
1224                                                 ast_verb(3, "Going to extension s|1 because of immediate=yes\n");
1225                                                 pri->pvts[chanpos]->exten[0] = 's';
1226                                                 pri->pvts[chanpos]->exten[1] = '\0';
1227                                         }
1228                                         /* Get called number */
1229                                         else if (!ast_strlen_zero(e->ring.callednum)) {
1230                                                 ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
1231                                         } else if (pri->overlapdial)
1232                                                 pri->pvts[chanpos]->exten[0] = '\0';
1233                                         else {
1234                                                 /* Some PRI circuits are set up to send _no_ digits.  Handle them as 's'. */
1235                                                 pri->pvts[chanpos]->exten[0] = 's';
1236                                                 pri->pvts[chanpos]->exten[1] = '\0';
1237                                         }
1238                                         /* No number yet, but received "sending complete"? */
1239                                         if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
1240                                                 ast_verb(3, "Going to extension s|1 because of Complete received\n");
1241                                                 pri->pvts[chanpos]->exten[0] = 's';
1242                                                 pri->pvts[chanpos]->exten[1] = '\0';
1243                                         }
1244
1245                                         /* Make sure extension exists (or in overlap dial mode, can exist) */
1246                                         if (((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
1247                                                 ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
1248                                                 /* Setup law */
1249                                                 if (e->ring.complete || !(pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
1250                                                         /* Just announce proceeding */
1251                                                         pri->pvts[chanpos]->proceeding = 1;
1252                                                         pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
1253                                                 } else {
1254                                                         if (pri->switchtype != PRI_SWITCH_GR303_TMC)
1255                                                                 pri_need_more_info(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
1256                                                         else
1257                                                                 pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
1258                                                 }
1259
1260                                                 /* Start PBX */
1261                                                 if (!e->ring.complete
1262                                                         && (pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
1263                                                         && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
1264                                                         /*
1265                                                          * Release the PRI lock while we create the channel
1266                                                          * so other threads can send D channel messages.
1267                                                          */
1268                                                         ast_mutex_unlock(&pri->lock);
1269                                                         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);
1270                                                         ast_mutex_lock(&pri->lock);
1271                                                         if (c) {
1272                                                                 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
1273                                                                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
1274                                                                 }
1275                                                                 if (e->ring.ani2 >= 0) {
1276                                                                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
1277                                                                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
1278                                                                 }
1279
1280 #ifdef SUPPORT_USERUSER
1281                                                                 if (!ast_strlen_zero(e->ring.useruserinfo)) {
1282                                                                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
1283                                                                 }
1284 #endif
1285
1286                                                                 snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
1287                                                                 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
1288                                                                 if (e->ring.redirectingreason >= 0)
1289                                                                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
1290 #if defined(HAVE_PRI_REVERSE_CHARGE)
1291                                                                 pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
1292 #endif
1293                                                         }
1294                                                         if (c && !ast_pthread_create_detached(&threadid, NULL, pri_ss_thread, pri->pvts[chanpos])) {
1295                                                                 ast_verb(3, "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
1296                                                                         plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
1297                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
1298                                                         } else {
1299                                                                 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
1300                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
1301                                                                 if (c)
1302                                                                         ast_hangup(c);
1303                                                                 else {
1304                                                                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
1305                                                                         pri->pvts[chanpos]->call = NULL;
1306                                                                 }
1307                                                         }
1308                                                 } else {
1309                                                         /*
1310                                                          * Release the PRI lock while we create the channel
1311                                                          * so other threads can send D channel messages.
1312                                                          */
1313                                                         ast_mutex_unlock(&pri->lock);
1314                                                         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);
1315                                                         ast_mutex_lock(&pri->lock);
1316                                                         if (c) {
1317                                                                 /*
1318                                                                  * It is reasonably safe to set the following
1319                                                                  * channel variables while the PRI and DAHDI private
1320                                                                  * structures are locked.  The PBX has not been
1321                                                                  * started yet and it is unlikely that any other task
1322                                                                  * will do anything with the channel we have just
1323                                                                  * created.
1324                                                                  */
1325                                                                 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
1326                                                                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
1327                                                                 }
1328                                                                 if (e->ring.ani2 >= 0) {
1329                                                                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
1330                                                                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
1331                                                                 }
1332
1333 #ifdef SUPPORT_USERUSER
1334                                                                 if (!ast_strlen_zero(e->ring.useruserinfo)) {
1335                                                                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
1336                                                                 }
1337 #endif
1338
1339                                                                 if (e->ring.redirectingreason >= 0)
1340                                                                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
1341 #if defined(HAVE_PRI_REVERSE_CHARGE)
1342                                                                 pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
1343 #endif
1344
1345                                                                 snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
1346                                                                 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
1347                                                         }
1348                                                         if (c && !ast_pbx_start(c)) {
1349                                                                 ast_verb(3, "Accepting call from '%s' to '%s' on channel %d/%d, span %d\n",
1350                                                                         plancallingnum, pri->pvts[chanpos]->exten,
1351                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
1352                                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
1353                                                         } else {
1354                                                                 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
1355                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
1356                                                                 if (c) {
1357                                                                         ast_hangup(c);
1358                                                                 } else {
1359                                                                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
1360                                                                         pri->pvts[chanpos]->call = NULL;
1361                                                                 }
1362                                                         }
1363                                                 }
1364                                         } else {
1365                                                 ast_verb(3, "Extension '%s' in context '%s' from '%s' does not exist.  Rejecting call on channel %d/%d, span %d\n",
1366                                                         pri->pvts[chanpos]->exten, pri->pvts[chanpos]->context, pri->pvts[chanpos]->cid_num, pri->pvts[chanpos]->logicalspan,
1367                                                         pri->pvts[chanpos]->prioffset, pri->span);
1368                                                 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_UNALLOCATED);
1369                                                 pri->pvts[chanpos]->call = NULL;
1370                                                 pri->pvts[chanpos]->exten[0] = '\0';
1371                                         }
1372                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1373                                 } else {
1374                                         if (e->ring.flexible)
1375                                                 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
1376                                         else
1377                                                 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
1378                                 }
1379                                 break;
1380                         case PRI_EVENT_RINGING:
1381                                 chanpos = pri_find_principle(pri, e->ringing.channel);
1382                                 if (chanpos < 0) {
1383                                         ast_log(LOG_WARNING, "Ringing requested on unconfigured channel %d/%d span %d\n",
1384                                                 PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
1385                                 } else {
1386                                         chanpos = pri_fixup_principle(pri, chanpos, e->ringing.call);
1387                                         if (chanpos < 0) {
1388                                                 ast_log(LOG_WARNING, "Ringing requested on channel %d/%d not in use on span %d\n",
1389                                                         PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
1390                                         } else {
1391                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1392                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
1393                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_RINGING, pri);
1394                                                 pri->pvts[chanpos]->alerting = 1;
1395
1396 #ifdef SUPPORT_USERUSER
1397                                                 if (!ast_strlen_zero(e->ringing.useruserinfo)) {
1398                                                         struct ast_channel *owner;
1399
1400                                                         sig_pri_lock_owner(pri, chanpos);
1401                                                         owner = pri->pvts[chanpos]->owner;
1402                                                         if (owner) {
1403                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
1404                                                                         e->ringing.useruserinfo);
1405                                                                 ast_channel_unlock(owner);
1406                                                         }
1407                                                 }
1408 #endif
1409
1410                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1411                                         }
1412                                 }
1413                                 break;
1414                         case PRI_EVENT_PROGRESS:
1415                                 /* Get chan value if e->e is not PRI_EVNT_RINGING */
1416                                 chanpos = pri_find_principle(pri, e->proceeding.channel);
1417                                 if (chanpos > -1) {
1418                                         if ((!pri->pvts[chanpos]->progress)
1419 #ifdef PRI_PROGRESS_MASK
1420                                                 || (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE)
1421 #else
1422                                                 || (e->proceeding.progress == 8)
1423 #endif
1424                                                 ) {
1425                                                 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, };
1426
1427                                                 if (e->proceeding.cause > -1) {
1428                                                         ast_verb(3, "PROGRESS with cause code %d received\n", e->proceeding.cause);
1429
1430                                                         /* Work around broken, out of spec USER_BUSY cause in a progress message */
1431                                                         if (e->proceeding.cause == AST_CAUSE_USER_BUSY) {
1432                                                                 if (pri->pvts[chanpos]->owner) {
1433                                                                         ast_verb(3, "PROGRESS with 'user busy' received, signaling AST_CONTROL_BUSY instead of AST_CONTROL_PROGRESS\n");
1434
1435                                                                         pri->pvts[chanpos]->owner->hangupcause = e->proceeding.cause;
1436                                                                         f.subclass = AST_CONTROL_BUSY;
1437                                                                 }
1438                                                         }
1439                                                 }
1440
1441                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1442                                                 ast_debug(1, "Queuing frame from PRI_EVENT_PROGRESS on channel %d/%d span %d\n",
1443                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
1444                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1445                                                 if (
1446 #ifdef PRI_PROGRESS_MASK
1447                                                         e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE
1448 #else
1449                                                         e->proceeding.progress == 8
1450 #endif
1451                                                         ) {
1452                                                         /* Bring voice path up */
1453                                                         f.subclass = AST_CONTROL_PROGRESS;
1454                                                         pri_queue_frame(pri->pvts[chanpos], &f, pri);
1455                                                 }
1456                                                 pri->pvts[chanpos]->progress = 1;
1457                                                 sig_pri_set_dialing(pri->pvts[chanpos], 0);
1458                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1459                                         }
1460                                 }
1461                                 break;
1462                         case PRI_EVENT_PROCEEDING:
1463                                 chanpos = pri_find_principle(pri, e->proceeding.channel);
1464                                 if (chanpos > -1) {
1465                                         if (!pri->pvts[chanpos]->proceeding) {
1466                                                 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROCEEDING, };
1467
1468                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1469                                                 ast_debug(1, "Queuing frame from PRI_EVENT_PROCEEDING on channel %d/%d span %d\n",
1470                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
1471                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1472                                                 if (
1473 #ifdef PRI_PROGRESS_MASK
1474                                                         e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE
1475 #else
1476                                                         e->proceeding.progress == 8
1477 #endif
1478                                                         ) {
1479                                                         /* Bring voice path up */
1480                                                         f.subclass = AST_CONTROL_PROGRESS;
1481                                                         pri_queue_frame(pri->pvts[chanpos], &f, pri);
1482                                                 }
1483                                                 pri->pvts[chanpos]->proceeding = 1;
1484                                                 sig_pri_set_dialing(pri->pvts[chanpos], 0);
1485                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1486                                         }
1487                                 }
1488                                 break;
1489                         case PRI_EVENT_FACNAME:
1490                                 chanpos = pri_find_principle(pri, e->facname.channel);
1491                                 if (chanpos < 0) {
1492                                         ast_log(LOG_WARNING, "Facility Name requested on unconfigured channel %d/%d span %d\n",
1493                                                 PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
1494                                 } else {
1495                                         chanpos = pri_fixup_principle(pri, chanpos, e->facname.call);
1496                                         if (chanpos < 0) {
1497                                                 ast_log(LOG_WARNING, "Facility Name requested on channel %d/%d not in use on span %d\n",
1498                                                         PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
1499                                         } else {
1500                                                 /* Re-use *69 field for PRI */
1501                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1502                                                 ast_copy_string(pri->pvts[chanpos]->lastcid_num, e->facname.callingnum, sizeof(pri->pvts[chanpos]->lastcid_num));
1503                                                 ast_copy_string(pri->pvts[chanpos]->lastcid_name, e->facname.callingname, sizeof(pri->pvts[chanpos]->lastcid_name));
1504                                                 pri_update_cid(pri->pvts[chanpos], pri);
1505                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
1506                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1507                                         }
1508                                 }
1509                                 break;
1510                         case PRI_EVENT_ANSWER:
1511                                 chanpos = pri_find_principle(pri, e->answer.channel);
1512                                 if (chanpos < 0) {
1513                                         ast_log(LOG_WARNING, "Answer on unconfigured channel %d/%d span %d\n",
1514                                                 PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
1515                                 } else {
1516                                         chanpos = pri_fixup_principle(pri, chanpos, e->answer.call);
1517                                         if (chanpos < 0) {
1518                                                 ast_log(LOG_WARNING, "Answer requested on channel %d/%d not in use on span %d\n",
1519                                                         PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
1520                                         } else {
1521                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1522                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_ANSWER, pri);
1523                                                 /* Enable echo cancellation if it's not on already */
1524                                                 sig_pri_set_dialing(pri->pvts[chanpos], 0);
1525                                                 sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
1526
1527 #ifdef SUPPORT_USERUSER
1528                                                 if (!ast_strlen_zero(e->answer.useruserinfo)) {
1529                                                         struct ast_channel *owner;
1530
1531                                                         sig_pri_lock_owner(pri, chanpos);
1532                                                         owner = pri->pvts[chanpos]->owner;
1533                                                         if (owner) {
1534                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
1535                                                                         e->answer.useruserinfo);
1536                                                                 ast_channel_unlock(owner);
1537                                                         }
1538                                                 }
1539 #endif
1540
1541                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1542                                         }
1543                                 }
1544                                 break;
1545                         case PRI_EVENT_HANGUP:
1546                                 chanpos = pri_find_principle(pri, e->hangup.channel);
1547                                 if (chanpos < 0) {
1548                                         ast_log(LOG_WARNING, "Hangup requested on unconfigured channel %d/%d span %d\n",
1549                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
1550                                 } else {
1551                                         chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
1552                                         if (chanpos > -1) {
1553                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1554                                                 if (!pri->pvts[chanpos]->alreadyhungup) {
1555                                                         /* we're calling here dahdi_hangup so once we get there we need to clear p->call after calling pri_hangup */
1556                                                         pri->pvts[chanpos]->alreadyhungup = 1;
1557                                                         if (pri->pvts[chanpos]->owner) {
1558                                                                 /* Queue a BUSY instead of a hangup if our cause is appropriate */
1559                                                                 pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
1560                                                                 if (pri->pvts[chanpos]->owner->_state == AST_STATE_UP)
1561                                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
1562                                                                 else {
1563                                                                         switch (e->hangup.cause) {
1564                                                                         case PRI_CAUSE_USER_BUSY:
1565                                                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_BUSY, pri);
1566                                                                                 break;
1567                                                                         case PRI_CAUSE_CALL_REJECTED:
1568                                                                         case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
1569                                                                         case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
1570                                                                         case PRI_CAUSE_SWITCH_CONGESTION:
1571                                                                         case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
1572                                                                         case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
1573                                                                                 pri_queue_control(pri->pvts[chanpos], AST_CONTROL_CONGESTION, pri);
1574                                                                                 break;
1575                                                                         default:
1576                                                                                 ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
1577                                                                                 break;
1578                                                                         }
1579                                                                 }
1580                                                         }
1581                                                         ast_verb(3, "Channel %d/%d, span %d got hangup, cause %d\n",
1582                                                                 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, e->hangup.cause);
1583                                                 } else {
1584                                                         pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
1585                                                         pri->pvts[chanpos]->call = NULL;
1586                                                 }
1587                                                 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
1588                                                         ast_verb(3, "Forcing restart of channel %d/%d on span %d since channel reported in use\n",
1589                                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
1590                                                         pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
1591                                                         pri->pvts[chanpos]->resetting = 1;
1592                                                 }
1593                                                 if (e->hangup.aoc_units > -1)
1594                                                         ast_verb(3, "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
1595                                                                 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
1596
1597 #ifdef SUPPORT_USERUSER
1598                                                 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
1599                                                         struct ast_channel *owner;
1600
1601                                                         sig_pri_lock_owner(pri, chanpos);
1602                                                         owner = pri->pvts[chanpos]->owner;
1603                                                         if (owner) {
1604                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
1605                                                                         e->hangup.useruserinfo);
1606                                                                 ast_channel_unlock(owner);
1607                                                         }
1608                                                 }
1609 #endif
1610
1611                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1612                                         } else {
1613                                                 ast_log(LOG_WARNING, "Hangup on bad channel %d/%d on span %d\n",
1614                                                         PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
1615                                         }
1616                                 }
1617                                 break;
1618 #ifndef PRI_EVENT_HANGUP_REQ
1619 #error please update libpri
1620 #endif
1621                         case PRI_EVENT_HANGUP_REQ:
1622                                 chanpos = pri_find_principle(pri, e->hangup.channel);
1623                                 if (chanpos < 0) {
1624                                         ast_log(LOG_WARNING, "Hangup REQ requested on unconfigured channel %d/%d span %d\n",
1625                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
1626                                 } else {
1627                                         chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
1628                                         if (chanpos > -1) {
1629                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1630                                                 if (pri->pvts[chanpos]->owner) {
1631                                                         pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
1632                                                         if (pri->pvts[chanpos]->owner->_state == AST_STATE_UP)
1633                                                                 ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
1634                                                         else {
1635                                                                 switch (e->hangup.cause) {
1636                                                                 case PRI_CAUSE_USER_BUSY:
1637                                                                         pri_queue_control(pri->pvts[chanpos], AST_CONTROL_BUSY, pri);
1638                                                                         break;
1639                                                                 case PRI_CAUSE_CALL_REJECTED:
1640                                                                 case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
1641                                                                 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
1642                                                                 case PRI_CAUSE_SWITCH_CONGESTION:
1643                                                                 case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
1644                                                                 case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
1645                                                                         pri_queue_control(pri->pvts[chanpos], AST_CONTROL_CONGESTION, pri);
1646                                                                         break;
1647                                                                 default:
1648                                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
1649                                                                         break;
1650                                                                 }
1651                                                         }
1652                                                         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);
1653                                                         if (e->hangup.aoc_units > -1)
1654                                                                 ast_verb(3, "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
1655                                                                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
1656                                                 } else {
1657                                                         pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
1658                                                         pri->pvts[chanpos]->call = NULL;
1659                                                 }
1660                                                 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
1661                                                         ast_verb(3, "Forcing restart of channel %d/%d span %d since channel reported in use\n",
1662                                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
1663                                                         pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
1664                                                         pri->pvts[chanpos]->resetting = 1;
1665                                                 }
1666
1667 #ifdef SUPPORT_USERUSER
1668                                                 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
1669                                                         struct ast_channel *owner;
1670
1671                                                         sig_pri_lock_owner(pri, chanpos);
1672                                                         owner = pri->pvts[chanpos]->owner;
1673                                                         if (owner) {
1674                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
1675                                                                         e->hangup.useruserinfo);
1676                                                                 ast_channel_unlock(owner);
1677                                                         }
1678                                                 }
1679 #endif
1680
1681                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1682                                         } else {
1683                                                 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);
1684                                         }
1685                                 }
1686                                 break;
1687                         case PRI_EVENT_HANGUP_ACK:
1688                                 chanpos = pri_find_principle(pri, e->hangup.channel);
1689                                 if (chanpos < 0) {
1690                                         ast_log(LOG_WARNING, "Hangup ACK requested on unconfigured channel number %d/%d span %d\n",
1691                                                 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
1692                                 } else {
1693                                         chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
1694                                         if (chanpos > -1) {
1695                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1696                                                 pri->pvts[chanpos]->call = NULL;
1697                                                 pri->pvts[chanpos]->resetting = 0;
1698                                                 if (pri->pvts[chanpos]->owner) {
1699                                                         ast_verb(3, "Channel %d/%d, span %d got hangup ACK\n", PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
1700                                                 }
1701
1702 #ifdef SUPPORT_USERUSER
1703                                                 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
1704                                                         struct ast_channel *owner;
1705
1706                                                         sig_pri_lock_owner(pri, chanpos);
1707                                                         owner = pri->pvts[chanpos]->owner;
1708                                                         if (owner) {
1709                                                                 pbx_builtin_setvar_helper(owner, "USERUSERINFO",
1710                                                                         e->hangup.useruserinfo);
1711                                                                 ast_channel_unlock(owner);
1712                                                         }
1713                                                 }
1714 #endif
1715
1716                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1717                                         }
1718                                 }
1719                                 break;
1720                         case PRI_EVENT_CONFIG_ERR:
1721                                 ast_log(LOG_WARNING, "PRI Error on span %d: %s\n", pri->trunkgroup, e->err.err);
1722                                 break;
1723                         case PRI_EVENT_RESTART_ACK:
1724                                 chanpos = pri_find_principle(pri, e->restartack.channel);
1725                                 if (chanpos < 0) {
1726                                         /* Sometime switches (e.g. I421 / British Telecom) don't give us the
1727                                            channel number, so we have to figure it out...  This must be why
1728                                            everybody resets exactly a channel at a time. */
1729                                         for (x = 0; x < pri->numchans; x++) {
1730                                                 if (pri->pvts[x] && pri->pvts[x]->resetting) {
1731                                                         chanpos = x;
1732                                                         sig_pri_lock_private(pri->pvts[chanpos]);
1733                                                         ast_debug(1, "Assuming restart ack is really for channel %d/%d span %d\n", pri->pvts[chanpos]->logicalspan,
1734                                                                 pri->pvts[chanpos]->prioffset, pri->span);
1735                                                         if (pri->pvts[chanpos]->owner) {
1736                                                                 ast_log(LOG_WARNING, "Got restart ack on channel %d/%d with owner on span %d\n", pri->pvts[chanpos]->logicalspan,
1737                                                                         pri->pvts[chanpos]->prioffset, pri->span);
1738                                                                 ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
1739                                                         }
1740                                                         pri->pvts[chanpos]->resetting = 0;
1741                                                         ast_verb(3, "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
1742                                                                 pri->pvts[chanpos]->prioffset, pri->span);
1743                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1744                                                         if (pri->resetting)
1745                                                                 pri_check_restart(pri);
1746                                                         break;
1747                                                 }
1748                                         }
1749                                         if (chanpos < 0) {
1750                                                 ast_log(LOG_WARNING, "Restart ACK requested on strange channel %d/%d span %d\n",
1751                                                         PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
1752                                         }
1753                                 } else {
1754                                         if (pri->pvts[chanpos]) {
1755                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1756                                                 if (pri->pvts[chanpos]->owner) {
1757                                                         ast_log(LOG_WARNING, "Got restart ack on channel %d/%d span %d with owner\n",
1758                                                                 PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
1759                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
1760                                                 }
1761                                                 pri->pvts[chanpos]->resetting = 0;
1762                                                 ast_verb(3, "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
1763                                                         pri->pvts[chanpos]->prioffset, pri->span);
1764                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1765                                                 if (pri->resetting)
1766                                                         pri_check_restart(pri);
1767                                         }
1768                                 }
1769                                 break;
1770                         case PRI_EVENT_SETUP_ACK:
1771                                 chanpos = pri_find_principle(pri, e->setup_ack.channel);
1772                                 if (chanpos < 0) {
1773                                         ast_log(LOG_WARNING, "Received SETUP_ACKNOWLEDGE on unconfigured channel %d/%d span %d\n",
1774                                                 PRI_SPAN(e->setup_ack.channel), PRI_CHANNEL(e->setup_ack.channel), pri->span);
1775                                 } else {
1776                                         chanpos = pri_fixup_principle(pri, chanpos, e->setup_ack.call);
1777                                         if (chanpos > -1) {
1778                                                 sig_pri_lock_private(pri->pvts[chanpos]);
1779                                                 pri->pvts[chanpos]->setup_ack = 1;
1780                                                 /* Send any queued digits */
1781                                                 for (x = 0;x < strlen(pri->pvts[chanpos]->dialdest); x++) {
1782                                                         ast_debug(1, "Sending pending digit '%c'\n", pri->pvts[chanpos]->dialdest[x]);
1783                                                         pri_information(pri->pri, pri->pvts[chanpos]->call,
1784                                                                 pri->pvts[chanpos]->dialdest[x]);
1785                                                 }
1786                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
1787                                         } else
1788                                                 ast_log(LOG_WARNING, "Unable to move channel %d!\n", e->setup_ack.channel);
1789                                 }
1790                                 break;
1791                         case PRI_EVENT_NOTIFY:
1792                                 chanpos = pri_find_principle(pri, e->notify.channel);
1793                                 if (chanpos < 0) {
1794                                         ast_log(LOG_WARNING, "Received NOTIFY on unconfigured channel %d/%d span %d\n",
1795                                                 PRI_SPAN(e->notify.channel), PRI_CHANNEL(e->notify.channel), pri->span);
1796                                 } else if (!pri->discardremoteholdretrieval) {
1797                                         struct ast_frame f = { AST_FRAME_CONTROL, };
1798
1799                                         sig_pri_lock_private(pri->pvts[chanpos]);
1800                                         switch (e->notify.info) {
1801                                         case PRI_NOTIFY_REMOTE_HOLD:
1802                                                 f.subclass = AST_CONTROL_HOLD;
1803                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1804                                                 break;
1805                                         case PRI_NOTIFY_REMOTE_RETRIEVAL:
1806                                                 f.subclass = AST_CONTROL_UNHOLD;
1807                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
1808                                                 break;
1809                                         }
1810                                         sig_pri_unlock_private(pri->pvts[chanpos]);
1811                                 }
1812                                 break;
1813                         default:
1814                                 ast_debug(1, "Event: %d\n", e->e);
1815                         }
1816                 }
1817                 ast_mutex_unlock(&pri->lock);
1818         }
1819         /* Never reached */
1820         return NULL;
1821 }
1822
1823 void sig_pri_init_pri(struct sig_pri_pri *pri)
1824 {
1825         int i;
1826
1827         memset(pri, 0, sizeof(*pri));
1828
1829         ast_mutex_init(&pri->lock);
1830
1831         pri->master = AST_PTHREADT_NULL;
1832         for (i = 0; i < NUM_DCHANS; i++)
1833                 pri->fds[i] = -1;
1834 }
1835
1836 int sig_pri_hangup(struct sig_pri_chan *p, struct ast_channel *ast)
1837 {
1838         int res = 0;
1839 #ifdef SUPPORT_USERUSER
1840         const char *useruser = pbx_builtin_getvar_helper(ast, "USERUSERINFO");
1841 #endif
1842
1843         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
1844         if (!ast->tech_pvt) {
1845                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1846                 return 0;
1847         }
1848
1849         p->owner = NULL;
1850         p->outgoing = 0;
1851         p->digital = 0;
1852         p->proceeding = 0;
1853         p->progress = 0;
1854         p->alerting = 0;
1855         p->setup_ack = 0;
1856         p->exten[0] = '\0';
1857         sig_pri_set_dialing(p, 0);
1858
1859         if (!p->call) {
1860                 res = 0;
1861                 goto exit;
1862         }
1863
1864         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
1865         if (!pri_grab(p, p->pri)) {
1866                 if (p->alreadyhungup) {
1867                         ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
1868
1869 #ifdef SUPPORT_USERUSER
1870                         pri_call_set_useruser(p->call, useruser);
1871 #endif
1872
1873                         pri_hangup(p->pri->pri, p->call, -1);
1874                         p->call = NULL;
1875                 } else {
1876                         const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
1877                         int icause = ast->hangupcause ? ast->hangupcause : -1;
1878                         ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
1879
1880 #ifdef SUPPORT_USERUSER
1881                         pri_call_set_useruser(p->call, useruser);
1882 #endif
1883
1884                         p->alreadyhungup = 1;
1885                         if (cause) {
1886                                 if (atoi(cause))
1887                                         icause = atoi(cause);
1888                         }
1889                         pri_hangup(p->pri->pri, p->call, icause);
1890                 }
1891                 if (res < 0)
1892                         ast_log(LOG_WARNING, "pri_disconnect failed\n");
1893                 pri_rel(p->pri);
1894         } else {
1895                 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
1896                 res = -1;
1897         }
1898
1899 exit:
1900         ast->tech_pvt = NULL;
1901         return res;
1902 }
1903
1904 int sig_pri_call(struct sig_pri_chan *p, struct ast_channel *ast, char *rdest, int timeout, int layer1)
1905 {
1906         char dest[256]; /* must be same length as p->dialdest */
1907         struct pri_sr *sr;
1908         char *c, *l, *n, *s = NULL;
1909 #ifdef SUPPORT_USERUSER
1910         const char *useruser;
1911 #endif
1912         int pridialplan;
1913         int dp_strip;
1914         int prilocaldialplan;
1915         int ldp_strip;
1916         int exclusive;
1917         const char *rr_str;
1918         int redirect_reason;
1919
1920         ast_log(LOG_DEBUG, "CALLING CID_NAME: %s CID_NUM:: %s\n", ast->cid.cid_name, ast->cid.cid_num);
1921
1922         if (!p->pri) {
1923                 ast_log(LOG_ERROR, "Could not find pri on channel %d\n", p->channel);
1924                 return -1;
1925         }
1926
1927
1928         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1929                 ast_log(LOG_WARNING, "sig_pri_call called on %s, neither down nor reserved\n", ast->name);
1930                 return -1;
1931         }
1932
1933         ast_copy_string(dest, rdest, sizeof(dest));
1934
1935         p->dialdest[0] = '\0';
1936         p->outgoing = 1;
1937
1938         c = strchr(dest, '/');
1939         if (c) {
1940                 c++;
1941         } else {
1942                 c = "";
1943         }
1944
1945         l = NULL;
1946         n = NULL;
1947         if (!p->hidecallerid) {
1948                 l = ast->connected.id.number;
1949                 if (!p->hidecalleridname) {
1950                         n = ast->connected.id.name;
1951                 }
1952         }
1953
1954         if (strlen(c) < p->stripmsd) {
1955                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1956                 return -1;
1957         }
1958         if (pri_grab(p, p->pri)) {
1959                 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
1960                 return -1;
1961         }
1962         if (!(p->call = pri_new_call(p->pri->pri))) {
1963                 ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
1964                 pri_rel(p->pri);
1965                 return -1;
1966         }
1967         if (!(sr = pri_sr_new())) {
1968                 ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
1969                 pri_destroycall(p->pri->pri, p->call);
1970                 p->call = NULL;
1971                 pri_rel(p->pri);
1972                 return -1;
1973         }
1974
1975         p->digital = IS_DIGITAL(ast->transfercapability);
1976
1977         /* Should the picked channel be used exclusively? */
1978         if (p->priexclusive || p->pri->nodetype == PRI_NETWORK) {
1979                 exclusive = 1;
1980         } else {
1981                 exclusive = 0;
1982         }
1983
1984         pri_sr_set_channel(sr, PVT_TO_CHANNEL(p), exclusive, 1);
1985         pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability,
1986                 (p->digital ? -1 : layer1));
1987
1988         if (p->pri->facilityenable)
1989                 pri_facility_enable(p->pri->pri);
1990
1991         ast_verb(3, "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
1992         dp_strip = 0;
1993         pridialplan = p->pri->dialplan - 1;
1994         if (pridialplan == -2 || pridialplan == -3) { /* compute dynamically */
1995                 if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
1996                         if (pridialplan == -2) {
1997                                 dp_strip = strlen(p->pri->internationalprefix);
1998                         }
1999                         pridialplan = PRI_INTERNATIONAL_ISDN;
2000                 } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2001                         if (pridialplan == -2) {
2002                                 dp_strip = strlen(p->pri->nationalprefix);
2003                         }
2004                         pridialplan = PRI_NATIONAL_ISDN;
2005                 } else {
2006                         pridialplan = PRI_LOCAL_ISDN;
2007                 }
2008         }
2009         while (c[p->stripmsd] > '9' && c[p->stripmsd] != '*' && c[p->stripmsd] != '#') {
2010                 switch (c[p->stripmsd]) {
2011                 case 'U':
2012                         pridialplan = (PRI_TON_UNKNOWN << 4) | (pridialplan & 0xf);
2013                         break;
2014                 case 'I':
2015                         pridialplan = (PRI_TON_INTERNATIONAL << 4) | (pridialplan & 0xf);
2016                         break;
2017                 case 'N':
2018                         pridialplan = (PRI_TON_NATIONAL << 4) | (pridialplan & 0xf);
2019                         break;
2020                 case 'L':
2021                         pridialplan = (PRI_TON_NET_SPECIFIC << 4) | (pridialplan & 0xf);
2022                         break;
2023                 case 'S':
2024                         pridialplan = (PRI_TON_SUBSCRIBER << 4) | (pridialplan & 0xf);
2025                         break;
2026                 case 'V':
2027                         pridialplan = (PRI_TON_ABBREVIATED << 4) | (pridialplan & 0xf);
2028                         break;
2029                 case 'R':
2030                         pridialplan = (PRI_TON_RESERVED << 4) | (pridialplan & 0xf);
2031                         break;
2032                 case 'u':
2033                         pridialplan = PRI_NPI_UNKNOWN | (pridialplan & 0xf0);
2034                         break;
2035                 case 'e':
2036                         pridialplan = PRI_NPI_E163_E164 | (pridialplan & 0xf0);
2037                         break;
2038                 case 'x':
2039                         pridialplan = PRI_NPI_X121 | (pridialplan & 0xf0);
2040                         break;
2041                 case 'f':
2042                         pridialplan = PRI_NPI_F69 | (pridialplan & 0xf0);
2043                         break;
2044                 case 'n':
2045                         pridialplan = PRI_NPI_NATIONAL | (pridialplan & 0xf0);
2046                         break;
2047                 case 'p':
2048                         pridialplan = PRI_NPI_PRIVATE | (pridialplan & 0xf0);
2049                         break;
2050                 case 'r':
2051                         pridialplan = PRI_NPI_RESERVED | (pridialplan & 0xf0);
2052                         break;
2053 #if defined(HAVE_PRI_REVERSE_CHARGE)
2054                 case 'C':
2055                         pri_sr_set_reversecharge(sr, PRI_REVERSECHARGE_REQUESTED);
2056                         break;
2057 #endif
2058                 default:
2059                         if (isalpha(c[p->stripmsd])) {
2060                                 ast_log(LOG_WARNING, "Unrecognized pridialplan %s modifier: %c\n",
2061                                         c[p->stripmsd] > 'Z' ? "NPI" : "TON", c[p->stripmsd]);
2062                         }
2063                         break;
2064                 }
2065                 c++;
2066         }
2067         pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2068
2069         ldp_strip = 0;
2070         prilocaldialplan = p->pri->localdialplan - 1;
2071         if ((l != NULL) && (prilocaldialplan == -2 || prilocaldialplan == -3)) { /* compute dynamically */
2072                 if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2073                         if (prilocaldialplan == -2) {
2074                                 ldp_strip = strlen(p->pri->internationalprefix);
2075                         }
2076                         prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2077                 } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2078                         if (prilocaldialplan == -2) {
2079                                 ldp_strip = strlen(p->pri->nationalprefix);
2080                         }
2081                         prilocaldialplan = PRI_NATIONAL_ISDN;
2082                 } else {
2083                         prilocaldialplan = PRI_LOCAL_ISDN;
2084                 }
2085         }
2086         if (l != NULL) {
2087                 while (*l > '9' && *l != '*' && *l != '#') {
2088                         switch (*l) {
2089                         case 'U':
2090                                 prilocaldialplan = (PRI_TON_UNKNOWN << 4) | (prilocaldialplan & 0xf);
2091                                 break;
2092                         case 'I':
2093                                 prilocaldialplan = (PRI_TON_INTERNATIONAL << 4) | (prilocaldialplan & 0xf);
2094                                 break;
2095                         case 'N':
2096                                 prilocaldialplan = (PRI_TON_NATIONAL << 4) | (prilocaldialplan & 0xf);
2097                                 break;
2098                         case 'L':
2099                                 prilocaldialplan = (PRI_TON_NET_SPECIFIC << 4) | (prilocaldialplan & 0xf);
2100                                 break;
2101                         case 'S':
2102                                 prilocaldialplan = (PRI_TON_SUBSCRIBER << 4) | (prilocaldialplan & 0xf);
2103                                 break;
2104                         case 'V':
2105                                 prilocaldialplan = (PRI_TON_ABBREVIATED << 4) | (prilocaldialplan & 0xf);
2106                                 break;
2107                         case 'R':
2108                                 prilocaldialplan = (PRI_TON_RESERVED << 4) | (prilocaldialplan & 0xf);
2109                                 break;
2110                         case 'u':
2111                                 prilocaldialplan = PRI_NPI_UNKNOWN | (prilocaldialplan & 0xf0);
2112                                 break;
2113                         case 'e':
2114                                 prilocaldialplan = PRI_NPI_E163_E164 | (prilocaldialplan & 0xf0);
2115                                 break;
2116                         case 'x':
2117                                 prilocaldialplan = PRI_NPI_X121 | (prilocaldialplan & 0xf0);
2118                                 break;
2119                         case 'f':
2120                                 prilocaldialplan = PRI_NPI_F69 | (prilocaldialplan & 0xf0);
2121                                 break;
2122                         case 'n':
2123                                 prilocaldialplan = PRI_NPI_NATIONAL | (prilocaldialplan & 0xf0);
2124                                 break;
2125                         case 'p':
2126                                 prilocaldialplan = PRI_NPI_PRIVATE | (prilocaldialplan & 0xf0);
2127                                 break;
2128                         case 'r':
2129                                 prilocaldialplan = PRI_NPI_RESERVED | (prilocaldialplan & 0xf0);
2130                                 break;
2131                         default:
2132                                 if (isalpha(*l)) {
2133                                         ast_log(LOG_WARNING,
2134                                                 "Unrecognized prilocaldialplan %s modifier: %c\n",
2135                                                 *l > 'Z' ? "NPI" : "TON", *l);
2136                                 }
2137                                 break;
2138                         }
2139                         l++;
2140                 }
2141         }
2142         pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2143                 p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2144         if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
2145                 if (!strcasecmp(rr_str, "UNKNOWN"))
2146                         redirect_reason = 0;
2147                 else if (!strcasecmp(rr_str, "BUSY"))
2148                         redirect_reason = 1;
2149                 else if (!strcasecmp(rr_str, "NO_REPLY"))
2150                         redirect_reason = 2;
2151                 else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
2152                         redirect_reason = 15;
2153                 else
2154                         redirect_reason = PRI_REDIR_UNCONDITIONAL;
2155         } else
2156                 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2157         pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
2158
2159 #ifdef SUPPORT_USERUSER
2160         /* User-user info */
2161         useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2162         if (useruser)
2163                 pri_sr_set_useruser(sr, useruser);
2164 #endif
2165
2166         if (pri_setup(p->pri->pri, p->call, sr)) {
2167                 ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n",
2168                         c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2169                 pri_rel(p->pri);
2170                 pri_sr_free(sr);
2171                 return -1;
2172         }
2173         pri_sr_free(sr);
2174         ast_setstate(ast, AST_STATE_DIALING);
2175         sig_pri_set_dialing(p, 1);
2176         pri_rel(p->pri);
2177         return 0;
2178 }
2179
2180 int sig_pri_indicate(struct sig_pri_chan *p, struct ast_channel *chan, int condition, const void *data, size_t datalen)
2181 {
2182         int res = -1;
2183
2184         switch (condition) {
2185         case AST_CONTROL_BUSY:
2186                 if (p->priindication_oob) {
2187                         chan->hangupcause = AST_CAUSE_USER_BUSY;
2188                         chan->_softhangup |= AST_SOFTHANGUP_DEV;
2189                         res = 0;
2190                 } else if (!p->progress && p->pri && !p->outgoing) {
2191                         if (p->pri->pri) {
2192                                 if (!pri_grab(p, p->pri)) {
2193 #ifdef HAVE_PRI_PROG_W_CAUSE
2194                                         pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, PRI_CAUSE_USER_BUSY); /* cause = 17 */
2195 #else
2196                                         pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
2197 #endif
2198                                         pri_rel(p->pri);
2199                                 } else {
2200                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2201                                 }
2202                         }
2203                         p->progress = 1;
2204                         res = sig_pri_play_tone(p, SIG_PRI_TONE_BUSY);
2205                 }
2206                 break;
2207         case AST_CONTROL_RINGING:
2208                 if ((!p->alerting) && p->pri && !p->outgoing && (chan->_state != AST_STATE_UP)) {
2209                         if (p->pri->pri) {
2210                                 if (!pri_grab(p, p->pri)) {
2211                                         pri_acknowledge(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
2212                                         pri_rel(p->pri);
2213                                 } else {
2214                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2215                                 }
2216                         }
2217                         p->alerting = 1;
2218                 }
2219                 res = sig_pri_play_tone(p, SIG_PRI_TONE_RINGTONE);
2220                 if (chan->_state != AST_STATE_UP) {
2221                         if (chan->_state != AST_STATE_RING)
2222                                 ast_setstate(chan, AST_STATE_RINGING);
2223                 }
2224                 break;
2225         case AST_CONTROL_PROCEEDING:
2226                 ast_debug(1,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
2227                 if (!p->proceeding && p->pri && !p->outgoing) {
2228                         if (p->pri->pri) {
2229                                 if (!pri_grab(p, p->pri)) {
2230                                         pri_proceeding(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
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                         }
2236                         p->proceeding = 1;
2237                         sig_pri_set_dialing(p, 0);
2238                 }
2239                 /* don't continue in ast_indicate */
2240                 res = 0;
2241                 break;
2242         case AST_CONTROL_PROGRESS:
2243                 ast_debug(1,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
2244                 p->digital = 0; /* Digital-only calls isn't allowing any inband progress messages */
2245                 if (!p->progress && p->pri && !p->outgoing) {
2246                         if (p->pri->pri) {
2247                                 if (!pri_grab(p, p->pri)) {
2248 #ifdef HAVE_PRI_PROG_W_CAUSE
2249                                         pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, -1);  /* no cause at all */
2250 #else
2251                                         pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
2252 #endif
2253                                         pri_rel(p->pri);
2254                                 } else {
2255                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2256                                 }
2257                         }
2258                         p->progress = 1;
2259                 }
2260                 /* don't continue in ast_indicate */
2261                 res = 0;
2262                 break;
2263         case AST_CONTROL_CONGESTION:
2264                 chan->hangupcause = AST_CAUSE_CONGESTION;
2265                 if (p->priindication_oob) {
2266                         chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
2267                         chan->_softhangup |= AST_SOFTHANGUP_DEV;
2268                         res = 0;
2269                 } else if (!p->progress && p->pri && !p->outgoing) {
2270                         if (p->pri) {
2271                                 if (!pri_grab(p, p->pri)) {
2272 #ifdef HAVE_PRI_PROG_W_CAUSE
2273                                         pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, PRI_CAUSE_SWITCH_CONGESTION); /* cause = 42 */
2274 #else
2275                                         pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
2276 #endif
2277                                         pri_rel(p->pri);
2278                                 } else {
2279                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2280                                 }
2281                         }
2282                         p->progress = 1;
2283                         res = sig_pri_play_tone(p, SIG_PRI_TONE_CONGESTION);
2284                 }
2285                 break;
2286         case AST_CONTROL_HOLD:
2287                 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
2288                         if (!pri_grab(p, p->pri)) {
2289                                 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_HOLD);
2290                                 pri_rel(p->pri);
2291                         } else {
2292                                 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
2293                         }
2294                 } else
2295                         ast_moh_start(chan, data, p->mohinterpret);
2296                 break;
2297         case AST_CONTROL_UNHOLD:
2298                 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
2299                         if (!pri_grab(p, p->pri)) {
2300                                 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_RETRIEVAL);
2301                                 pri_rel(p->pri);
2302                         }
2303                 } else
2304                         ast_moh_stop(chan);
2305                 break;
2306         case AST_CONTROL_SRCUPDATE:
2307                 res = 0;
2308                 break;
2309         case -1:
2310                 res = sig_pri_play_tone(p, -1);
2311                 break;
2312         }
2313
2314         return res;
2315 }
2316
2317 int sig_pri_answer(struct sig_pri_chan *p, struct ast_channel *ast)
2318 {
2319         int res = 0;
2320         /* Send a pri acknowledge */
2321         if (!pri_grab(p, p->pri)) {
2322                 p->proceeding = 1;
2323                 sig_pri_set_dialing(p, 0);
2324                 res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2325                 pri_rel(p->pri);
2326         } else {
2327                 res = -1;
2328         }
2329         ast_setstate(ast, AST_STATE_UP);
2330         return res;
2331 }
2332
2333 int sig_pri_available(struct sig_pri_chan *p, int channelmatch, ast_group_t groupmatch, int *reason, int *channelmatched, int *groupmatched)
2334 {
2335         /* If no owner definitely available */
2336         if (!p->owner) {
2337                 /* Trust PRI */
2338                 if (p->pri) {
2339 #ifdef HAVE_PRI_SERVICE_MESSAGES
2340                         char db_chan_name[20], db_answer[5], state;
2341                         int why = 0;
2342
2343                         snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, p->pri->span, p->channel);
2344                         if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
2345                                 sscanf(db_answer, "%c:%d", &state, &why);
2346                         }
2347                         if ((p->resetting || p->call) || (why)) {
2348                                 if (why) {
2349                                         *reason = AST_CAUSE_REQUESTED_CHAN_UNAVAIL;
2350                                 }
2351 #else
2352                         if (p->resetting || p->call) {
2353 #endif
2354                                 return 0;
2355                         } else {
2356                                 return 1;
2357                         }
2358                 }
2359         }
2360
2361         return 0;
2362 }
2363
2364 /* If return 0, it means this function was able to handle it (pre setup digits).  If non zero, the user of this
2365  * functions should handle it normally (generate inband DTMF) */
2366 int sig_pri_digit_begin(struct sig_pri_chan *pvt, struct ast_channel *ast, char digit)
2367 {
2368         if ((ast->_state == AST_STATE_DIALING) && !pvt->proceeding) {
2369                 if (pvt->setup_ack) {
2370                         if (!pri_grab(pvt, pvt->pri)) {
2371                                 pri_information(pvt->pri->pri, pvt->call, digit);
2372                                 pri_rel(pvt->pri);
2373                         } else {
2374                                 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->pri->span);
2375                         }
2376                 } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
2377                         int res;
2378                         ast_debug(1, "Queueing digit '%c' since setup_ack not yet received\n", digit);
2379                         res = strlen(pvt->dialdest);
2380                         pvt->dialdest[res++] = digit;
2381                         pvt->dialdest[res] = '\0';
2382                 }
2383                 return 0;
2384         }
2385         return 1;
2386 }
2387
2388 int sig_pri_start_pri(struct sig_pri_pri *pri)
2389 {
2390         int x;
2391         int i;
2392
2393         ast_mutex_init(&pri->lock);
2394
2395         for (i = 0; i < NUM_DCHANS; i++) {
2396                 if (pri->fds[i] == -1) {
2397                         break;
2398                 }
2399
2400                 switch (pri->sig) {
2401                 case SIG_BRI:
2402                         pri->dchans[i] = pri_new_bri(pri->fds[i], 1, pri->nodetype, pri->switchtype);
2403                         break;
2404                 case SIG_BRI_PTMP:
2405                         pri->dchans[i] = pri_new_bri(pri->fds[i], 0, pri->nodetype, pri->switchtype);
2406                         break;
2407                 default:
2408                         pri->dchans[i] = pri_new(pri->fds[i], pri->nodetype, pri->switchtype);
2409 #ifdef HAVE_PRI_SERVICE_MESSAGES
2410                         if (pri->enable_service_message_support) {
2411                                 pri_set_service_message_support(pri->dchans[i], 1);
2412                         }
2413 #endif
2414                         break;
2415                 }
2416
2417                 pri_set_overlapdial(pri->dchans[i], (pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING) ? 1 : 0);
2418 #ifdef HAVE_PRI_PROG_W_CAUSE
2419                 pri_set_chan_mapping_logical(pri->dchans[i], pri->qsigchannelmapping == DAHDI_CHAN_MAPPING_LOGICAL);
2420 #endif
2421 #ifdef HAVE_PRI_INBANDDISCONNECT
2422                 pri_set_inbanddisconnect(pri->dchans[i], pri->inbanddisconnect);
2423 #endif
2424                 /* Enslave to master if appropriate */
2425                 if (i)
2426                         pri_enslave(pri->dchans[0], pri->dchans[i]);
2427                 if (!pri->dchans[i]) {
2428                         if (pri->fds[i] > 0)
2429                                 close(pri->fds[i]);
2430                         pri->fds[i] = -1;
2431                         ast_log(LOG_ERROR, "Unable to create PRI structure\n");
2432                         return -1;
2433                 }
2434                 pri_set_debug(pri->dchans[i], DEFAULT_PRI_DEBUG);
2435                 pri_set_nsf(pri->dchans[i], pri->nsf);
2436 #ifdef PRI_GETSET_TIMERS
2437                 for (x = 0; x < PRI_MAX_TIMERS; x++) {
2438                         if (pri->pritimers[x] != 0)
2439                                 pri_set_timer(pri->dchans[i], x, pri->pritimers[x]);
2440                 }
2441 #endif
2442         }
2443         /* Assume primary is the one we use */
2444         pri->pri = pri->dchans[0];
2445         pri->resetpos = -1;
2446         if (ast_pthread_create_background(&pri->master, NULL, pri_dchannel, pri)) {
2447                 for (i = 0; i < NUM_DCHANS; i++) {
2448                         if (!pri->dchans[i])
2449                                 break;
2450                         if (pri->fds[i] > 0)
2451                                 close(pri->fds[i]);
2452                         pri->fds[i] = -1;
2453                 }
2454                 ast_log(LOG_ERROR, "Unable to spawn D-channel: %s\n", strerror(errno));
2455                 return -1;
2456         }
2457         return 0;
2458 }
2459
2460 void sig_pri_chan_alarm_notify(struct sig_pri_chan *p, int noalarm)
2461 {
2462         if (!noalarm) {
2463                 p->inalarm = 1;
2464                 if (!p->pri || !p->pri->pri || (pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0)) {
2465                         /* T309 is not enabled : hangup calls when alarm occurs */
2466                         if (p->call) {
2467                                 if (p->pri && p->pri->pri) {
2468                                         if (!pri_grab(p, p->pri)) {
2469                                                 pri_hangup(p->pri->pri, p->call, -1);
2470                                                 pri_destroycall(p->pri->pri, p->call);
2471                                                 p->call = NULL;
2472                                                 pri_rel(p->pri);
2473                                         } else
2474                                                 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2475                                 } else
2476                                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2477                         } else
2478                                 ast_log(LOG_WARNING, "The PRI Call has not been destroyed\n");
2479                 }
2480                 if (p->owner)
2481                         ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
2482         } else {
2483                 p->inalarm = 0;
2484         }
2485 }
2486
2487 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)
2488 {
2489         struct sig_pri_chan *p;
2490
2491         p = ast_calloc(1, sizeof(*p));
2492
2493         if (!p)
2494                 return p;
2495
2496         p->logicalspan = logicalspan;
2497         p->prioffset = channo;
2498         p->mastertrunkgroup = trunkgroup;
2499
2500         p->calls = callback;
2501         p->chan_pvt = pvt_data;
2502
2503         pri->pvts[pri->numchans++] = p;
2504         p->pri = pri;
2505