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