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