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