Separate the uses of NUM_DCHANS and MAX_CHANNELS into PRI, SS7, and MFCR2 users.
[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/app.h"
39 #include "asterisk/file.h"
40 #include "asterisk/callerid.h"
41 #include "asterisk/say.h"
42 #include "asterisk/manager.h"
43 #include "asterisk/astdb.h"
44 #include "asterisk/causes.h"
45 #include "asterisk/musiconhold.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/transcap.h"
48 #include "asterisk/features.h"
49
50 #include "sig_pri.h"
51 #ifndef PRI_EVENT_FACILITY
52 #error please update libpri
53 #endif
54
55 /* define this to send PRI user-user information elements */
56 #undef SUPPORT_USERUSER
57
58 #if defined(HAVE_PRI_CCSS)
59 struct sig_pri_cc_agent_prv {
60         /*! Asterisk span D channel control structure. */
61         struct sig_pri_pri *pri;
62         /*! CC id value to use with libpri. -1 if invalid. */
63         long cc_id;
64         /*! TRUE if CC has been requested and we are waiting for the response. */
65         unsigned char cc_request_response_pending;
66 };
67
68 struct sig_pri_cc_monitor_instance {
69         /*! \brief Asterisk span D channel control structure. */
70         struct sig_pri_pri *pri;
71         /*! CC id value to use with libpri. (-1 if already canceled). */
72         long cc_id;
73         /*! CC core id value. */
74         int core_id;
75         /*! Device name(Channel name less sequence number) */
76         char name[1];
77 };
78
79 /*! Upper level agent/monitor type name. */
80 static const char *sig_pri_cc_type_name;
81 /*! Container of sig_pri monitor instances. */
82 static struct ao2_container *sig_pri_cc_monitors;
83 #endif  /* defined(HAVE_PRI_CCSS) */
84
85 static int pri_matchdigittimeout = 3000;
86
87 static int pri_gendigittimeout = 8000;
88
89 #define DCHAN_NOTINALARM  (1 << 0)
90 #define DCHAN_UP          (1 << 1)
91
92 /* Defines to help decode the encoded event channel id. */
93 #define PRI_CHANNEL(p)  ((p) & 0xff)
94 #define PRI_SPAN(p)             (((p) >> 8) & 0xff)
95 #define PRI_EXPLICIT    (1 << 16)
96 #define PRI_CIS_CALL    (1 << 17)       /* Call is using the D channel only. */
97 #define PRI_HELD_CALL   (1 << 18)
98
99
100 #define DCHAN_AVAILABLE (DCHAN_NOTINALARM | DCHAN_UP)
101
102 #define PRI_DEADLOCK_AVOIDANCE(p) \
103         do { \
104                 sig_pri_unlock_private(p); \
105                 usleep(1); \
106                 sig_pri_lock_private(p); \
107         } while (0)
108
109 static int pri_active_dchan_index(struct sig_pri_pri *pri);
110
111 static inline void pri_rel(struct sig_pri_pri *pri)
112 {
113         ast_mutex_unlock(&pri->lock);
114 }
115
116 static unsigned int PVT_TO_CHANNEL(struct sig_pri_chan *p)
117 {
118         int res = (((p)->prioffset) | ((p)->logicalspan << 8) | (p->mastertrunkgroup ? PRI_EXPLICIT : 0));
119         ast_debug(5, "prioffset: %d mastertrunkgroup: %d logicalspan: %d result: %d\n",
120                 p->prioffset, p->mastertrunkgroup, p->logicalspan, res);
121
122         return res;
123 }
124
125 static void sig_pri_handle_dchan_exception(struct sig_pri_pri *pri, int index)
126 {
127         if (pri->calls->handle_dchan_exception)
128                 pri->calls->handle_dchan_exception(pri, index);
129 }
130
131 static void sig_pri_set_dialing(struct sig_pri_chan *p, int flag)
132 {
133         if (p->calls->set_dialing)
134                 p->calls->set_dialing(p->chan_pvt, flag);
135 }
136
137 static void sig_pri_set_digital(struct sig_pri_chan *p, int flag)
138 {
139         p->digital = flag;
140         if (p->calls->set_digital)
141                 p->calls->set_digital(p->chan_pvt, flag);
142 }
143
144 static const char *sig_pri_get_orig_dialstring(struct sig_pri_chan *p)
145 {
146         if (p->calls->get_orig_dialstring) {
147                 return p->calls->get_orig_dialstring(p->chan_pvt);
148         }
149         ast_log(LOG_ERROR, "get_orig_dialstring callback not defined\n");
150         return "";
151 }
152
153 #if defined(HAVE_PRI_CCSS)
154 static void sig_pri_make_cc_dialstring(struct sig_pri_chan *p, char *buf, size_t buf_size)
155 {
156         if (p->calls->make_cc_dialstring) {
157                 p->calls->make_cc_dialstring(p->chan_pvt, buf, buf_size);
158         } else {
159                 ast_log(LOG_ERROR, "make_cc_dialstring callback not defined\n");
160                 buf[0] = '\0';
161         }
162 }
163 #endif  /* defined(HAVE_PRI_CCSS) */
164
165 /*!
166  * \internal
167  * \brief Reevaluate the PRI span device state.
168  * \since 1.8
169  *
170  * \param pri Asterisk D channel control structure.
171  *
172  * \return Nothing
173  *
174  * \note Assumes the pri->lock is already obtained.
175  */
176 static void sig_pri_span_devstate_changed(struct sig_pri_pri *pri)
177 {
178         if (pri->calls->update_span_devstate) {
179                 pri->calls->update_span_devstate(pri);
180         }
181 }
182
183 /*!
184  * \internal
185  * \brief Set the caller id information in the parent module.
186  * \since 1.8
187  *
188  * \param p sig_pri channel structure.
189  *
190  * \return Nothing
191  */
192 static void sig_pri_set_caller_id(struct sig_pri_chan *p)
193 {
194         struct ast_party_caller caller;
195
196         if (p->calls->set_callerid) {
197                 ast_party_caller_init(&caller);
198                 caller.id.number = p->cid_num;
199                 caller.id.name = p->cid_name;
200                 if (!ast_strlen_zero(p->cid_subaddr)) {
201                         caller.id.subaddress.valid = 1;
202                         //caller.id.subaddress.type = 0;/* nsap */
203                         //caller.id.subaddress.odd_even_indicator = 0;
204                         caller.id.subaddress.str = p->cid_subaddr;
205                 }
206                 caller.id.number_type = p->cid_ton;
207                 caller.id.number_presentation = p->callingpres;
208                 caller.ani = p->cid_ani;
209                 caller.ani2 = p->cid_ani2;
210                 p->calls->set_callerid(p->chan_pvt, &caller);
211         }
212 }
213
214 /*!
215  * \internal
216  * \brief Set the Dialed Number Identifier.
217  * \since 1.8
218  *
219  * \param p sig_pri channel structure.
220  * \param dnid Dialed Number Identifier string.
221  *
222  * \return Nothing
223  */
224 static void sig_pri_set_dnid(struct sig_pri_chan *p, const char *dnid)
225 {
226         if (p->calls->set_dnid) {
227                 p->calls->set_dnid(p->chan_pvt, dnid);
228         }
229 }
230
231 /*!
232  * \internal
233  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
234  * \since 1.8
235  *
236  * \param p sig_pri channel structure.
237  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
238  *
239  * \return Nothing
240  */
241 static void sig_pri_set_rdnis(struct sig_pri_chan *p, const char *rdnis)
242 {
243         if (p->calls->set_rdnis) {
244                 p->calls->set_rdnis(p->chan_pvt, rdnis);
245         }
246 }
247
248 static void sig_pri_unlock_private(struct sig_pri_chan *p)
249 {
250         if (p->calls->unlock_private)
251                 p->calls->unlock_private(p->chan_pvt);
252 }
253
254 static void sig_pri_lock_private(struct sig_pri_chan *p)
255 {
256         if (p->calls->lock_private)
257                 p->calls->lock_private(p->chan_pvt);
258 }
259
260 static inline int pri_grab(struct sig_pri_chan *p, struct sig_pri_pri *pri)
261 {
262         int res;
263         /* Grab the lock first */
264         do {
265                 res = ast_mutex_trylock(&pri->lock);
266                 if (res) {
267                         PRI_DEADLOCK_AVOIDANCE(p);
268                 }
269         } while (res);
270         /* Then break the poll */
271         pthread_kill(pri->master, SIGURG);
272         return 0;
273 }
274
275 /*!
276  * \internal
277  * \brief Convert PRI redirecting reason to asterisk version.
278  * \since 1.8
279  *
280  * \param pri_reason PRI redirecting reason.
281  *
282  * \return Equivalent asterisk redirecting reason value.
283  */
284 static enum AST_REDIRECTING_REASON pri_to_ast_reason(int pri_reason)
285 {
286         enum AST_REDIRECTING_REASON ast_reason;
287
288         switch (pri_reason) {
289         case PRI_REDIR_FORWARD_ON_BUSY:
290                 ast_reason = AST_REDIRECTING_REASON_USER_BUSY;
291                 break;
292         case PRI_REDIR_FORWARD_ON_NO_REPLY:
293                 ast_reason = AST_REDIRECTING_REASON_NO_ANSWER;
294                 break;
295         case PRI_REDIR_DEFLECTION:
296                 ast_reason = AST_REDIRECTING_REASON_DEFLECTION;
297                 break;
298         case PRI_REDIR_UNCONDITIONAL:
299                 ast_reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
300                 break;
301         case PRI_REDIR_UNKNOWN:
302         default:
303                 ast_reason = AST_REDIRECTING_REASON_UNKNOWN;
304                 break;
305         }
306
307         return ast_reason;
308 }
309
310 /*!
311  * \internal
312  * \brief Convert asterisk redirecting reason to PRI version.
313  * \since 1.8
314  *
315  * \param ast_reason Asterisk redirecting reason.
316  *
317  * \return Equivalent PRI redirecting reason value.
318  */
319 static int ast_to_pri_reason(enum AST_REDIRECTING_REASON ast_reason)
320 {
321         int pri_reason;
322
323         switch (ast_reason) {
324         case AST_REDIRECTING_REASON_USER_BUSY:
325                 pri_reason = PRI_REDIR_FORWARD_ON_BUSY;
326                 break;
327         case AST_REDIRECTING_REASON_NO_ANSWER:
328                 pri_reason = PRI_REDIR_FORWARD_ON_NO_REPLY;
329                 break;
330         case AST_REDIRECTING_REASON_UNCONDITIONAL:
331                 pri_reason = PRI_REDIR_UNCONDITIONAL;
332                 break;
333         case AST_REDIRECTING_REASON_DEFLECTION:
334                 pri_reason = PRI_REDIR_DEFLECTION;
335                 break;
336         case AST_REDIRECTING_REASON_UNKNOWN:
337         default:
338                 pri_reason = PRI_REDIR_UNKNOWN;
339                 break;
340         }
341
342         return pri_reason;
343 }
344
345 /*!
346  * \internal
347  * \brief Convert PRI number presentation to asterisk version.
348  * \since 1.8
349  *
350  * \param pri_presentation PRI number presentation.
351  *
352  * \return Equivalent asterisk number presentation value.
353  */
354 static int pri_to_ast_presentation(int pri_presentation)
355 {
356         int ast_presentation;
357
358         switch (pri_presentation) {
359         case PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
360                 ast_presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
361                 break;
362         case PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
363                 ast_presentation = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
364                 break;
365         case PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
366                 ast_presentation = AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN;
367                 break;
368         case PRES_ALLOWED_NETWORK_NUMBER:
369                 ast_presentation = AST_PRES_ALLOWED_NETWORK_NUMBER;
370                 break;
371         case PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
372                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
373                 break;
374         case PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
375                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
376                 break;
377         case PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
378                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN;
379                 break;
380         case PRES_PROHIB_NETWORK_NUMBER:
381                 ast_presentation = AST_PRES_PROHIB_NETWORK_NUMBER;
382                 break;
383         case PRES_NUMBER_NOT_AVAILABLE:
384                 ast_presentation = AST_PRES_NUMBER_NOT_AVAILABLE;
385                 break;
386         default:
387                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
388                 break;
389         }
390
391         return ast_presentation;
392 }
393
394 /*!
395  * \internal
396  * \brief Convert asterisk number presentation to PRI version.
397  * \since 1.8
398  *
399  * \param ast_presentation Asterisk number presentation.
400  *
401  * \return Equivalent PRI number presentation value.
402  */
403 static int ast_to_pri_presentation(int ast_presentation)
404 {
405         int pri_presentation;
406
407         switch (ast_presentation) {
408         case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
409                 pri_presentation = PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
410                 break;
411         case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
412                 pri_presentation = PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
413                 break;
414         case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
415                 pri_presentation = PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN;
416                 break;
417         case AST_PRES_ALLOWED_NETWORK_NUMBER:
418                 pri_presentation = PRES_ALLOWED_NETWORK_NUMBER;
419                 break;
420         case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
421                 pri_presentation = PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
422                 break;
423         case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
424                 pri_presentation = PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
425                 break;
426         case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
427                 pri_presentation = PRES_PROHIB_USER_NUMBER_FAILED_SCREEN;
428                 break;
429         case AST_PRES_PROHIB_NETWORK_NUMBER:
430                 pri_presentation = PRES_PROHIB_NETWORK_NUMBER;
431                 break;
432         case AST_PRES_NUMBER_NOT_AVAILABLE:
433                 pri_presentation = PRES_NUMBER_NOT_AVAILABLE;
434                 break;
435         default:
436                 pri_presentation = PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
437                 break;
438         }
439
440         return pri_presentation;
441 }
442
443 /*!
444  * \internal
445  * \brief Determine the overall presentation value for the given party.
446  * \since 1.8
447  *
448  * \param id Party to determine the overall presentation value.
449  *
450  * \return Overall presentation value for the given party converted to ast values.
451  */
452 static int overall_ast_presentation(const struct pri_party_id *id)
453 {
454         int number_priority;
455         int number_value;
456         int number_screening;
457         int name_priority;
458         int name_value;
459
460         /* Determine name presentation priority. */
461         if (!id->name.valid) {
462                 name_value = PRI_PRES_UNAVAILABLE;
463                 name_priority = 3;
464         } else {
465                 name_value = id->name.presentation & PRI_PRES_RESTRICTION;
466                 switch (name_value) {
467                 case PRI_PRES_RESTRICTED:
468                         name_priority = 0;
469                         break;
470                 case PRI_PRES_ALLOWED:
471                         name_priority = 1;
472                         break;
473                 case PRI_PRES_UNAVAILABLE:
474                         name_priority = 2;
475                         break;
476                 default:
477                         name_value = PRI_PRES_UNAVAILABLE;
478                         name_priority = 3;
479                         break;
480                 }
481         }
482
483         /* Determine number presentation priority. */
484         if (!id->number.valid) {
485                 number_screening = PRI_PRES_USER_NUMBER_UNSCREENED;
486                 number_value = PRI_PRES_UNAVAILABLE;
487                 number_priority = 3;
488         } else {
489                 number_screening = id->number.presentation & PRI_PRES_NUMBER_TYPE;
490                 number_value = id->number.presentation & PRI_PRES_RESTRICTION;
491                 switch (number_value) {
492                 case PRI_PRES_RESTRICTED:
493                         number_priority = 0;
494                         break;
495                 case PRI_PRES_ALLOWED:
496                         number_priority = 1;
497                         break;
498                 case PRI_PRES_UNAVAILABLE:
499                         number_priority = 2;
500                         break;
501                 default:
502                         number_screening = PRI_PRES_USER_NUMBER_UNSCREENED;
503                         number_value = PRI_PRES_UNAVAILABLE;
504                         number_priority = 3;
505                         break;
506                 }
507         }
508
509         /* Select the wining presentation value. */
510         if (name_priority < number_priority) {
511                 number_value = name_value;
512         }
513
514         return pri_to_ast_presentation(number_value | number_screening);
515 }
516
517 #if defined(HAVE_PRI_SUBADDR)
518 /*!
519  * \internal
520  * \brief Fill in the asterisk party subaddress from the given PRI party subaddress.
521  * \since 1.8
522  *
523  * \param ast_subaddress Asterisk party subaddress structure.
524  * \param pri_subaddress PRI party subaddress structure.
525  *
526  * \return Nothing
527  *
528  */
529 static void sig_pri_set_subaddress(struct ast_party_subaddress *ast_subaddress, const struct pri_party_subaddress *pri_subaddress)
530 {
531         char *cnum, *ptr;
532         int x, len;
533
534         if (ast_subaddress->str) {
535                 ast_free(ast_subaddress->str);
536         }
537         if (pri_subaddress->length <= 0) {
538                 ast_party_subaddress_init(ast_subaddress);
539                 return;
540         }
541
542         if (!pri_subaddress->type) {
543                 /* NSAP */
544                 ast_subaddress->str = ast_strdup((char *) pri_subaddress->data);
545         } else {
546                 /* User Specified */
547                 if (!(cnum = ast_malloc(2 * pri_subaddress->length + 1))) {
548                         ast_party_subaddress_init(ast_subaddress);
549                         return;
550                 }
551
552                 ptr = cnum;
553                 len = pri_subaddress->length - 1; /* -1 account for zero based indexing */
554                 for (x = 0; x < len; ++x) {
555                         ptr += sprintf(ptr, "%02x", pri_subaddress->data[x]);
556                 }
557
558                 if (pri_subaddress->odd_even_indicator) {
559                         /* ODD */
560                         sprintf(ptr, "%01x", (pri_subaddress->data[len]) >> 4);
561                 } else {
562                         /* EVEN */
563                         sprintf(ptr, "%02x", pri_subaddress->data[len]);
564                 }
565                 ast_subaddress->str = cnum;
566         }
567         ast_subaddress->type = pri_subaddress->type;
568         ast_subaddress->odd_even_indicator = pri_subaddress->odd_even_indicator;
569         ast_subaddress->valid = 1;
570 }
571 #endif  /* defined(HAVE_PRI_SUBADDR) */
572
573 #if defined(HAVE_PRI_SUBADDR)
574 static unsigned char ast_pri_pack_hex_char(char c)
575 {
576         unsigned char res;
577
578         if (c < '0') {
579                 res = 0;
580         } else if (c < ('9' + 1)) {
581                 res = c - '0';
582         } else if (c < 'A') {
583                 res = 0;
584         } else if (c < ('F' + 1)) {
585                 res = c - 'A' + 10;
586         } else if (c < 'a') {
587                 res = 0;
588         } else if (c < ('f' + 1)) {
589                 res = c - 'a' + 10;
590         } else {
591                 res = 0;
592         }
593         return res;
594 }
595 #endif  /* defined(HAVE_PRI_SUBADDR) */
596
597 #if defined(HAVE_PRI_SUBADDR)
598 /*!
599  * \internal
600  * \brief Convert a null terminated hexadecimal string to a packed hex byte array.
601  * \details left justified, with 0 padding if odd length.
602  * \since 1.8
603  *
604  * \param dst pointer to packed byte array.
605  * \param src pointer to null terminated hexadecimal string.
606  * \param maxlen destination array size.
607  *
608  * \return Length of byte array
609  *
610  * \note The dst is not an ASCIIz string.
611  * \note The src is an ASCIIz hex string.
612  */
613 static int ast_pri_pack_hex_string(unsigned char *dst, char *src, int maxlen)
614 {
615         int res = 0;
616         int len = strlen(src);
617
618         if (len > (2 * maxlen)) {
619                 len = 2 * maxlen;
620         }
621
622         res = len / 2 + len % 2;
623
624         while (len > 1) {
625                 *dst = ast_pri_pack_hex_char(*src) << 4;
626                 src++;
627                 *dst |= ast_pri_pack_hex_char(*src);
628                 dst++, src++;
629                 len -= 2;
630         }
631         if (len) { /* 1 left */
632                 *dst = ast_pri_pack_hex_char(*src) << 4;
633         }
634         return res;
635 }
636 #endif  /* defined(HAVE_PRI_SUBADDR) */
637
638 #if defined(HAVE_PRI_SUBADDR)
639 /*!
640  * \internal
641  * \brief Fill in the PRI party subaddress from the given asterisk party subaddress.
642  * \since 1.8
643  *
644  * \param pri_subaddress PRI party subaddress structure.
645  * \param ast_subaddress Asterisk party subaddress structure.
646  *
647  * \return Nothing
648  *
649  * \note Assumes that pri_subaddress has been previously memset to zero.
650  */
651 static void sig_pri_party_subaddress_from_ast(struct pri_party_subaddress *pri_subaddress, const struct ast_party_subaddress *ast_subaddress)
652 {
653         if (ast_subaddress->valid && !ast_strlen_zero(ast_subaddress->str)) {
654                 pri_subaddress->type = ast_subaddress->type;
655                 if (!ast_subaddress->type) {
656                         /* 0 = NSAP */
657                         ast_copy_string((char *) pri_subaddress->data, ast_subaddress->str,
658                                 sizeof(pri_subaddress->data));
659                         pri_subaddress->length = strlen((char *) pri_subaddress->data);
660                         pri_subaddress->odd_even_indicator = 0;
661                         pri_subaddress->valid = 1;
662                 } else {
663                         /* 2 = User Specified */
664                         /*
665                          * Copy HexString to packed HexData,
666                          * if odd length then right pad trailing byte with 0
667                          */
668                         int length = ast_pri_pack_hex_string(pri_subaddress->data,
669                                 ast_subaddress->str, sizeof(pri_subaddress->data));
670
671                         pri_subaddress->length = length;
672                         pri_subaddress->odd_even_indicator = (length & 1);
673                         pri_subaddress->valid = 1;
674                 }
675         }
676 }
677 #endif  /* defined(HAVE_PRI_SUBADDR) */
678
679 /*!
680  * \internal
681  * \brief Fill in the PRI party id from the given asterisk party id.
682  * \since 1.8
683  *
684  * \param pri_id PRI party id structure.
685  * \param ast_id Asterisk party id structure.
686  *
687  * \return Nothing
688  *
689  * \note Assumes that pri_id has been previously memset to zero.
690  */
691 static void sig_pri_party_id_from_ast(struct pri_party_id *pri_id, const struct ast_party_id *ast_id)
692 {
693         int presentation;
694
695         presentation = ast_to_pri_presentation(ast_id->number_presentation);
696         if (!ast_strlen_zero(ast_id->name)) {
697                 pri_id->name.valid = 1;
698                 pri_id->name.presentation = presentation;
699                 pri_id->name.char_set = PRI_CHAR_SET_ISO8859_1;
700                 ast_copy_string(pri_id->name.str, ast_id->name, sizeof(pri_id->name.str));
701         }
702         if (!ast_strlen_zero(ast_id->number)) {
703                 pri_id->number.valid = 1;
704                 pri_id->number.presentation = presentation;
705                 pri_id->number.plan = ast_id->number_type;
706                 ast_copy_string(pri_id->number.str, ast_id->number, sizeof(pri_id->number.str));
707         }
708 #if defined(HAVE_PRI_SUBADDR)
709         sig_pri_party_subaddress_from_ast(&pri_id->subaddress, &ast_id->subaddress);
710 #endif  /* defined(HAVE_PRI_SUBADDR) */
711 }
712
713 /*!
714  * \internal
715  * \brief Update the PRI redirecting information for the current call.
716  * \since 1.8
717  *
718  * \param pvt sig_pri private channel structure.
719  * \param ast Asterisk channel
720  *
721  * \return Nothing
722  *
723  * \note Assumes that the PRI lock is already obtained.
724  */
725 static void sig_pri_redirecting_update(struct sig_pri_chan *pvt, struct ast_channel *ast)
726 {
727         struct pri_party_redirecting pri_redirecting;
728
729 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
730
731         memset(&pri_redirecting, 0, sizeof(pri_redirecting));
732         sig_pri_party_id_from_ast(&pri_redirecting.from, &ast->redirecting.from);
733         sig_pri_party_id_from_ast(&pri_redirecting.to, &ast->redirecting.to);
734         pri_redirecting.count = ast->redirecting.count;
735         pri_redirecting.reason = ast_to_pri_reason(ast->redirecting.reason);
736
737         pri_redirecting_update(pvt->pri->pri, pvt->call, &pri_redirecting);
738 }
739
740 /*!
741  * \internal
742  * \brief Reset DTMF detector.
743  * \since 1.8
744  *
745  * \param p sig_pri channel structure.
746  *
747  * \return Nothing
748  */
749 static void sig_pri_dsp_reset_and_flush_digits(struct sig_pri_chan *p)
750 {
751         if (p->calls->dsp_reset_and_flush_digits) {
752                 p->calls->dsp_reset_and_flush_digits(p->chan_pvt);
753         }
754 }
755
756 static int sig_pri_set_echocanceller(struct sig_pri_chan *p, int enable)
757 {
758         if (p->calls->set_echocanceller)
759                 return p->calls->set_echocanceller(p->chan_pvt, enable);
760         else
761                 return -1;
762 }
763
764 static void sig_pri_fixup_chans(struct sig_pri_chan *old_chan, struct sig_pri_chan *new_chan)
765 {
766         if (old_chan->calls->fixup_chans)
767                 old_chan->calls->fixup_chans(old_chan->chan_pvt, new_chan->chan_pvt);
768 }
769
770 static int sig_pri_play_tone(struct sig_pri_chan *p, enum sig_pri_tone tone)
771 {
772         if (p->calls->play_tone)
773                 return p->calls->play_tone(p->chan_pvt, tone);
774         else
775                 return -1;
776 }
777
778 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)
779 {
780         struct ast_channel *c;
781
782         if (p->calls->new_ast_channel)
783                 c = p->calls->new_ast_channel(p->chan_pvt, state, startpbx, ulaw, transfercapability, exten, requestor);
784         else
785                 return NULL;
786
787         if (!p->owner)
788                 p->owner = c;
789         p->isidlecall = 0;
790         p->alreadyhungup = 0;
791         if (transfercapability & AST_TRANS_CAP_DIGITAL) {
792                 c->transfercapability = transfercapability;
793                 pbx_builtin_setvar_helper(c, "TRANSFERCAPABILITY", ast_transfercapability2str(transfercapability));
794                 sig_pri_set_digital(p, 1);
795         }
796         if (p->pri && !pri_grab(p, p->pri)) {
797                 sig_pri_span_devstate_changed(p->pri);
798                 pri_rel(p->pri);
799         } else {
800                 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
801         }
802
803         return c;
804 }
805
806 struct ast_channel *sig_pri_request(struct sig_pri_chan *p, enum sig_pri_law law, const struct ast_channel *requestor, int transfercapability)
807 {
808         struct ast_channel *ast;
809
810         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
811
812         p->outgoing = 1;
813         ast = sig_pri_new_ast_channel(p, AST_STATE_RESERVED, 0, law, transfercapability, p->exten, requestor);
814         if (!ast) {
815                 p->outgoing = 0;
816         }
817         return ast;
818 }
819
820 int pri_is_up(struct sig_pri_pri *pri)
821 {
822         int x;
823         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
824                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
825                         return 1;
826         }
827         return 0;
828 }
829
830 static char *pri_order(int level)
831 {
832         switch (level) {
833         case 0:
834                 return "Primary";
835         case 1:
836                 return "Secondary";
837         case 2:
838                 return "Tertiary";
839         case 3:
840                 return "Quaternary";
841         default:
842                 return "<Unknown>";
843         }
844 }
845
846 /* Returns index of the active dchan */
847 static int pri_active_dchan_index(struct sig_pri_pri *pri)
848 {
849         int x;
850
851         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
852                 if ((pri->dchans[x] == pri->pri))
853                         return x;
854         }
855
856         ast_log(LOG_WARNING, "No active dchan found!\n");
857         return -1;
858 }
859
860 static int pri_find_dchan(struct sig_pri_pri *pri)
861 {
862         int oldslot = -1;
863         struct pri *old;
864         int newslot = -1;
865         int x;
866         old = pri->pri;
867         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
868                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
869                         newslot = x;
870                 if (pri->dchans[x] == old) {
871                         oldslot = x;
872                 }
873         }
874         if (newslot < 0) {
875                 newslot = 0;
876                 /* This is annoying to see on non persistent layer 2 connections.  Let's not complain in that case */
877                 if (pri->sig != SIG_BRI_PTMP) {
878                         ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel as D-channel anyway!\n");
879                 }
880         }
881         if (old && (oldslot != newslot))
882                 ast_log(LOG_NOTICE, "Switching from d-channel fd %d to fd %d!\n",
883                         pri->fds[oldslot], pri->fds[newslot]);
884         pri->pri = pri->dchans[newslot];
885         return 0;
886 }
887
888 static void pri_queue_frame(struct sig_pri_chan *p, struct ast_frame *f, struct sig_pri_pri *pri)
889 {
890         /* We must unlock the PRI to avoid the possibility of a deadlock */
891         if (pri)
892                 ast_mutex_unlock(&pri->lock);
893         for (;;) {
894                 if (p->owner) {
895                         if (ast_channel_trylock(p->owner)) {
896                                 PRI_DEADLOCK_AVOIDANCE(p);
897                         } else {
898                                 ast_queue_frame(p->owner, f);
899                                 ast_channel_unlock(p->owner);
900                                 break;
901                         }
902                 } else
903                         break;
904         }
905         if (pri)
906                 ast_mutex_lock(&pri->lock);
907 }
908
909 static void pri_queue_control(struct sig_pri_chan *p, int subclass, struct sig_pri_pri *pri)
910 {
911         struct ast_frame f = {AST_FRAME_CONTROL, };
912
913         if (p->calls->queue_control) {
914                 p->calls->queue_control(p->chan_pvt, subclass);
915         }
916
917         f.subclass.integer = subclass;
918         pri_queue_frame(p, &f, pri);
919 }
920
921 static int pri_find_principle(struct sig_pri_pri *pri, int channel, q931_call *call)
922 {
923         int x;
924         int span;
925         int principle;
926
927         if (channel < 0) {
928                 /* Channel is not picked yet. */
929                 return -1;
930         }
931
932         if (channel & PRI_HELD_CALL) {
933                 if (!call) {
934                         /* Cannot find a held call without a call. */
935                         return -1;
936                 }
937                 principle = -1;
938                 for (x = 0; x < pri->numchans; ++x) {
939                         if (pri->pvts[x]
940                                 && pri->pvts[x]->call == call) {
941                                 principle = x;
942                                 break;
943                         }
944                 }
945                 return principle;
946         }
947
948         span = PRI_SPAN(channel);
949         if (!(channel & PRI_EXPLICIT)) {
950                 int index;
951
952                 index = pri_active_dchan_index(pri);
953                 if (index == -1) {
954                         return -1;
955                 }
956                 span = pri->dchan_logical_span[index];
957         }
958
959         channel = PRI_CHANNEL(channel);
960         principle = -1;
961         for (x = 0; x < pri->numchans; x++) {
962                 if (pri->pvts[x]
963                         && pri->pvts[x]->prioffset == channel
964                         && pri->pvts[x]->logicalspan == span
965                         && !pri->pvts[x]->no_b_channel) {
966                         principle = x;
967                         break;
968                 }
969         }
970
971         return principle;
972 }
973
974 static int pri_fixup_principle(struct sig_pri_pri *pri, int principle, q931_call *call)
975 {
976         int x;
977
978         if (principle < 0 || pri->numchans <= principle) {
979                 /* Out of rannge */
980                 return -1;
981         }
982         if (!call) {
983                 /* No call */
984                 return principle;
985         }
986         if (pri->pvts[principle] && pri->pvts[principle]->call == call) {
987                 /* Call is already on the specified principle. */
988                 return principle;
989         }
990
991         /* Find the old principle location. */
992         for (x = 0; x < pri->numchans; x++) {
993                 struct sig_pri_chan *new_chan;
994                 struct sig_pri_chan *old_chan;
995
996                 if (!pri->pvts[x] || pri->pvts[x]->call != call) {
997                         continue;
998                 }
999
1000                 /* Found our call */
1001                 new_chan = pri->pvts[principle];
1002                 old_chan = pri->pvts[x];
1003
1004                 ast_verb(3, "Moving call from channel %d to channel %d\n",
1005                         old_chan->channel, new_chan->channel);
1006                 if (new_chan->owner) {
1007                         ast_log(LOG_WARNING,
1008                                 "Can't fix up channel from %d to %d because %d is already in use\n",
1009                                 old_chan->channel, new_chan->channel, new_chan->channel);
1010                         return -1;
1011                 }
1012
1013                 sig_pri_fixup_chans(old_chan, new_chan);
1014
1015                 /* Fix it all up now */
1016                 new_chan->owner = old_chan->owner;
1017                 old_chan->owner = NULL;
1018
1019                 new_chan->call = old_chan->call;
1020                 old_chan->call = NULL;
1021
1022                 /* Transfer flags from the old channel. */
1023                 new_chan->alerting = old_chan->alerting;
1024                 new_chan->alreadyhungup = old_chan->alreadyhungup;
1025                 new_chan->isidlecall = old_chan->isidlecall;
1026                 new_chan->proceeding = old_chan->proceeding;
1027                 new_chan->progress = old_chan->progress;
1028                 new_chan->setup_ack = old_chan->setup_ack;
1029                 new_chan->outgoing = old_chan->outgoing;
1030                 new_chan->digital = old_chan->digital;
1031                 old_chan->alerting = 0;
1032                 old_chan->alreadyhungup = 0;
1033                 old_chan->isidlecall = 0;
1034                 old_chan->proceeding = 0;
1035                 old_chan->progress = 0;
1036                 old_chan->setup_ack = 0;
1037                 old_chan->outgoing = 0;
1038                 old_chan->digital = 0;
1039
1040                 /* More stuff to transfer to the new channel. */
1041 #if defined(HAVE_PRI_REVERSE_CHARGE)
1042                 new_chan->reverse_charging_indication = old_chan->reverse_charging_indication;
1043 #endif  /* defined(HAVE_PRI_REVERSE_CHARGE) */
1044 #if defined(HAVE_PRI_SETUP_KEYPAD)
1045                 strcpy(new_chan->keypad_digits, old_chan->keypad_digits);
1046 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
1047
1048                 if (new_chan->no_b_channel) {
1049                         /* Copy the real channel configuration to the no B channel interface. */
1050                         new_chan->hidecallerid = old_chan->hidecallerid;
1051                         new_chan->hidecalleridname = old_chan->hidecalleridname;
1052                         new_chan->immediate = old_chan->immediate;
1053                         new_chan->priexclusive = old_chan->priexclusive;
1054                         new_chan->priindication_oob = old_chan->priindication_oob;
1055                         new_chan->use_callerid = old_chan->use_callerid;
1056                         new_chan->use_callingpres = old_chan->use_callingpres;
1057                         new_chan->stripmsd = old_chan->stripmsd;
1058                         strcpy(new_chan->context, old_chan->context);
1059                         strcpy(new_chan->mohinterpret, old_chan->mohinterpret);
1060
1061                         /* Become a member of the old channel span/trunk-group. */
1062                         new_chan->logicalspan = old_chan->logicalspan;
1063                         new_chan->mastertrunkgroup = old_chan->mastertrunkgroup;
1064                 }
1065
1066                 return principle;
1067         }
1068         ast_log(LOG_WARNING, "Call specified, but not found?\n");
1069         return -1;
1070 }
1071
1072 static char * redirectingreason2str(int redirectingreason)
1073 {
1074         switch (redirectingreason) {
1075         case 0:
1076                 return "UNKNOWN";
1077         case 1:
1078                 return "BUSY";
1079         case 2:
1080                 return "NO_REPLY";
1081         case 0xF:
1082                 return "UNCONDITIONAL";
1083         default:
1084                 return "NOREDIRECT";
1085         }
1086 }
1087
1088 static char *dialplan2str(int dialplan)
1089 {
1090         if (dialplan == -1) {
1091                 return("Dynamically set dialplan in ISDN");
1092         }
1093         return (pri_plan2str(dialplan));
1094 }
1095
1096 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_pri *pri, const char *number, const int plan)
1097 {
1098         switch (plan) {
1099         case PRI_INTERNATIONAL_ISDN:            /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
1100                 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
1101                 break;
1102         case PRI_NATIONAL_ISDN:                 /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
1103                 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
1104                 break;
1105         case PRI_LOCAL_ISDN:                    /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
1106                 snprintf(buf, size, "%s%s", pri->localprefix, number);
1107                 break;
1108         case PRI_PRIVATE:                       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
1109                 snprintf(buf, size, "%s%s", pri->privateprefix, number);
1110                 break;
1111         case PRI_UNKNOWN:                       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
1112                 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
1113                 break;
1114         default:                                /* other Q.931 dialplan => don't twiddle with callingnum */
1115                 snprintf(buf, size, "%s", number);
1116                 break;
1117         }
1118 }
1119
1120 /*! \note Assumes the pri->lock is already obtained. */
1121 static int pri_check_restart(struct sig_pri_pri *pri)
1122 {
1123 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1124 tryanotherpos:
1125 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1126         do {
1127                 pri->resetpos++;
1128         } while (pri->resetpos < pri->numchans
1129                 && (!pri->pvts[pri->resetpos]
1130                         || pri->pvts[pri->resetpos]->no_b_channel
1131                         || pri->pvts[pri->resetpos]->call
1132                         || pri->pvts[pri->resetpos]->resetting));
1133         if (pri->resetpos < pri->numchans) {
1134 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1135                 unsigned why;
1136
1137                 why = pri->pvts[pri->resetpos]->service_status;
1138                 if (why) {
1139                         ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), not sending RESTART\n", pri->span,
1140                                 pri->pvts[pri->resetpos]->channel, (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
1141                         goto tryanotherpos;
1142                 }
1143 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1144
1145                 /* Mark the channel as resetting and restart it */
1146                 pri->pvts[pri->resetpos]->resetting = 1;
1147                 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
1148         } else {
1149                 pri->resetting = 0;
1150                 time(&pri->lastreset);
1151         }
1152         return 0;
1153 }
1154
1155 static int pri_find_empty_chan(struct sig_pri_pri *pri, int backwards)
1156 {
1157         int x;
1158         if (backwards)
1159                 x = pri->numchans;
1160         else
1161                 x = 0;
1162         for (;;) {
1163                 if (backwards && (x < 0))
1164                         break;
1165                 if (!backwards && (x >= pri->numchans))
1166                         break;
1167                 if (pri->pvts[x]
1168                         && !pri->pvts[x]->no_b_channel
1169                         && !pri->pvts[x]->inalarm
1170                         && !pri->pvts[x]->owner) {
1171                         ast_debug(1, "Found empty available channel %d/%d\n",
1172                                 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
1173                         return x;
1174                 }
1175                 if (backwards)
1176                         x--;
1177                 else
1178                         x++;
1179         }
1180         return -1;
1181 }
1182
1183 #if defined(HAVE_PRI_CALL_HOLD)
1184 /*!
1185  * \internal
1186  * \brief Find or create an empty no-B-channel interface to use.
1187  * \since 1.8
1188  *
1189  * \param pri sig_pri span controller to find interface.
1190  *
1191  * \note Assumes the pri->lock is already obtained.
1192  *
1193  * \retval array-index into private pointer array on success.
1194  * \retval -1 on error.
1195  */
1196 static int pri_find_empty_nobch(struct sig_pri_pri *pri)
1197 {
1198         int idx;
1199
1200         for (idx = 0; idx < pri->numchans; ++idx) {
1201                 if (pri->pvts[idx]
1202                         && pri->pvts[idx]->no_b_channel
1203                         && !pri->pvts[idx]->inalarm
1204                         && !pri->pvts[idx]->owner) {
1205                         ast_debug(1, "Found empty available no B channel interface\n");
1206                         return idx;
1207                 }
1208         }
1209
1210         /* Need to create a new interface. */
1211         if (pri->calls->new_nobch_intf) {
1212                 idx = pri->calls->new_nobch_intf(pri);
1213         } else {
1214                 idx = -1;
1215         }
1216         return idx;
1217 }
1218 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1219
1220 #if defined(HAVE_PRI_CALL_HOLD)
1221 /*!
1222  * \internal
1223  * \brief Find the channel associated with the libpri call.
1224  * \since 1.8
1225  *
1226  * \param pri sig_pri span controller to find interface.
1227  * \param call LibPRI opaque call pointer to find.
1228  *
1229  * \note Assumes the pri->lock is already obtained.
1230  *
1231  * \retval array-index into private pointer array on success.
1232  * \retval -1 on error.
1233  */
1234 static int pri_find_pri_call(struct sig_pri_pri *pri, q931_call *call)
1235 {
1236         int idx;
1237
1238         for (idx = 0; idx < pri->numchans; ++idx) {
1239                 if (pri->pvts[idx] && pri->pvts[idx]->call == call) {
1240                         /* Found the channel */
1241                         return idx;
1242                 }
1243         }
1244         return -1;
1245 }
1246 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1247
1248 static void *do_idle_thread(void *v_pvt)
1249 {
1250         struct sig_pri_chan *pvt = v_pvt;
1251         struct ast_channel *chan = pvt->owner;
1252         struct ast_frame *f;
1253         char ex[80];
1254         /* Wait up to 30 seconds for an answer */
1255         int newms, ms = 30000;
1256
1257         ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
1258         snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
1259         if (ast_call(chan, ex, 0)) {
1260                 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
1261                 ast_hangup(chan);
1262                 return NULL;
1263         }
1264         while ((newms = ast_waitfor(chan, ms)) > 0) {
1265                 f = ast_read(chan);
1266                 if (!f) {
1267                         /* Got hangup */
1268                         break;
1269                 }
1270                 if (f->frametype == AST_FRAME_CONTROL) {
1271                         switch (f->subclass.integer) {
1272                         case AST_CONTROL_ANSWER:
1273                                 /* Launch the PBX */
1274                                 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
1275                                 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
1276                                 chan->priority = 1;
1277                                 ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
1278                                 ast_pbx_run(chan);
1279                                 /* It's already hungup, return immediately */
1280                                 return NULL;
1281                         case AST_CONTROL_BUSY:
1282                                 ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
1283                                 break;
1284                         case AST_CONTROL_CONGESTION:
1285                                 ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
1286                                 break;
1287                         };
1288                 }
1289                 ast_frfree(f);
1290                 ms = newms;
1291         }
1292         /* Hangup the channel since nothing happend */
1293         ast_hangup(chan);
1294         return NULL;
1295 }
1296
1297 static void *pri_ss_thread(void *data)
1298 {
1299         struct sig_pri_chan *p = data;
1300         struct ast_channel *chan = p->owner;
1301         char exten[AST_MAX_EXTENSION];
1302         int res;
1303         int len;
1304         int timeout;
1305
1306         if (!chan) {
1307                 /* We lost the owner before we could get started. */
1308                 return NULL;
1309         }
1310
1311         /*
1312          * In the bizarre case where the channel has become a zombie before we
1313          * even get started here, abort safely.
1314          */
1315         if (!chan->tech_pvt) {
1316                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
1317                 ast_hangup(chan);
1318                 return NULL;
1319         }
1320
1321         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
1322
1323         sig_pri_dsp_reset_and_flush_digits(p);
1324
1325         /* Now loop looking for an extension */
1326         ast_copy_string(exten, p->exten, sizeof(exten));
1327         len = strlen(exten);
1328         res = 0;
1329         while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
1330                 if (len && !ast_ignore_pattern(chan->context, exten))
1331                         sig_pri_play_tone(p, -1);
1332                 else
1333                         sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
1334                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
1335                         timeout = pri_matchdigittimeout;
1336                 else
1337                         timeout = pri_gendigittimeout;
1338                 res = ast_waitfordigit(chan, timeout);
1339                 if (res < 0) {
1340                         ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
1341                         ast_hangup(chan);
1342                         return NULL;
1343                 } else if (res) {
1344                         exten[len++] = res;
1345                         exten[len] = '\0';
1346                 } else
1347                         goto exit;
1348         }
1349         /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
1350         if (ast_strlen_zero(exten)) {
1351                 ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
1352                 exten[0] = 's';
1353                 exten[1] = '\0';
1354         } else {
1355                 if (chan->cid.cid_dnid) {
1356                         ast_free(chan->cid.cid_dnid);
1357                 }
1358                 chan->cid.cid_dnid = ast_strdup(exten);
1359         }
1360         sig_pri_play_tone(p, -1);
1361         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
1362                 /* Start the real PBX */
1363                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1364                 sig_pri_dsp_reset_and_flush_digits(p);
1365                 if (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) {
1366                         if (p->pri->pri) {              
1367                                 if (!pri_grab(p, p->pri)) {
1368                                         pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
1369                                         p->proceeding = 1;
1370                                         pri_rel(p->pri);
1371                                 } else {
1372                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
1373                                 }
1374                         }
1375                 }
1376
1377                 sig_pri_set_echocanceller(p, 1);
1378                 ast_setstate(chan, AST_STATE_RING);
1379                 res = ast_pbx_run(chan);
1380                 if (res) {
1381                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
1382                 }
1383         } else {
1384                 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
1385                 chan->hangupcause = AST_CAUSE_UNALLOCATED;
1386                 ast_hangup(chan);
1387                 p->exten[0] = '\0';
1388                 /* Since we send release complete here, we won't get one */
1389                 p->call = NULL;
1390         }
1391         return NULL;
1392
1393 exit:
1394         res = sig_pri_play_tone(p, SIG_PRI_TONE_CONGESTION);
1395         if (res < 0)
1396                 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
1397         ast_hangup(chan);
1398         return NULL;
1399 }
1400
1401 void pri_event_alarm(struct sig_pri_pri *pri, int index, int before_start_pri)
1402 {
1403         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
1404         if (!before_start_pri)
1405                 pri_find_dchan(pri);
1406 }
1407
1408 void pri_event_noalarm(struct sig_pri_pri *pri, int index, int before_start_pri)
1409 {
1410         pri->dchanavail[index] |= DCHAN_NOTINALARM;
1411         if (!before_start_pri)
1412                 pri_restart(pri->dchans[index]);
1413 }
1414
1415 /*!
1416  * \internal
1417  * \brief Convert libpri party id into asterisk party id.
1418  * \since 1.8
1419  *
1420  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
1421  * \param pri_id libpri party id structure containing source information.
1422  * \param pri Span controlling structure.
1423  *
1424  * \note The filled in ast_id structure needs to be destroyed by
1425  * ast_party_id_free() when it is no longer needed.
1426  *
1427  * \return Nothing
1428  */
1429 static void sig_pri_party_id_convert(struct ast_party_id *ast_id,
1430         const struct pri_party_id *pri_id, struct sig_pri_pri *pri)
1431 {
1432         char number[AST_MAX_EXTENSION];
1433
1434         if (pri_id->name.valid) {
1435                 ast_id->name = ast_strdup(pri_id->name.str);
1436         }
1437         if (pri_id->number.valid) {
1438                 apply_plan_to_number(number, sizeof(number), pri, pri_id->number.str,
1439                         pri_id->number.plan);
1440                 ast_id->number = ast_strdup(number);
1441                 ast_id->number_type = pri_id->number.plan;
1442         }
1443         if (pri_id->name.valid || pri_id->number.valid) {
1444                 ast_id->number_presentation = overall_ast_presentation(pri_id);
1445         }
1446 #if defined(HAVE_PRI_SUBADDR)
1447         if (pri_id->subaddress.valid) {
1448                 sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
1449         }
1450 #endif  /* defined(HAVE_PRI_SUBADDR) */
1451 }
1452
1453 /*!
1454  * \internal
1455  * \brief Convert libpri redirecting information into asterisk redirecting information.
1456  * \since 1.8
1457  *
1458  * \param ast_redirecting Asterisk redirecting structure to fill.
1459  * \param pri_redirecting libpri redirecting structure containing source information.
1460  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
1461  * \param pri Span controlling structure.
1462  *
1463  * \note The filled in ast_redirecting structure needs to be destroyed by
1464  * ast_party_redirecting_free() when it is no longer needed.
1465  *
1466  * \return Nothing
1467  */
1468 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
1469         const struct pri_party_redirecting *pri_redirecting,
1470         const struct ast_party_redirecting *ast_guide,
1471         struct sig_pri_pri *pri)
1472 {
1473         ast_party_redirecting_set_init(ast_redirecting, ast_guide);
1474
1475         sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
1476         sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
1477         ast_redirecting->count = pri_redirecting->count;
1478         ast_redirecting->reason = pri_to_ast_reason(pri_redirecting->reason);
1479 }
1480
1481 /*!
1482  * \internal
1483  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
1484  * \since 1.8
1485  *
1486  * \param msn_patterns Comma separated list of MSN patterns to match.
1487  * \param exten Extension to match in the MSN list.
1488  *
1489  * \retval 1 if matches.
1490  * \retval 0 if no match.
1491  */
1492 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
1493 {
1494         char *pattern;
1495         char *msn_list;
1496         char *list_tail;
1497
1498         msn_list = strdupa(msn_patterns);
1499
1500         list_tail = NULL;
1501         pattern = strtok_r(msn_list, ",", &list_tail);
1502         while (pattern) {
1503                 pattern = ast_strip(pattern);
1504                 if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
1505                         /* Extension matched the pattern. */
1506                         return 1;
1507                 }
1508                 pattern = strtok_r(NULL, ",", &list_tail);
1509         }
1510         /* Did not match any pattern in the list. */
1511         return 0;
1512 }
1513
1514 /*!
1515  * \internal
1516  * \brief Obtain the sig_pri owner channel lock if the owner exists.
1517  * \since 1.8
1518  *
1519  * \param pri sig_pri PRI control structure.
1520  * \param chanpos Channel position in the span.
1521  *
1522  * \note Assumes the pri->lock is already obtained.
1523  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1524  *
1525  * \return Nothing
1526  */
1527 static void sig_pri_lock_owner(struct sig_pri_pri *pri, int chanpos)
1528 {
1529         for (;;) {
1530                 if (!pri->pvts[chanpos]->owner) {
1531                         /* There is no owner lock to get. */
1532                         break;
1533                 }
1534                 if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
1535                         /* We got the lock */
1536                         break;
1537                 }
1538                 /* We must unlock the PRI to avoid the possibility of a deadlock */
1539                 ast_mutex_unlock(&pri->lock);
1540                 PRI_DEADLOCK_AVOIDANCE(pri->pvts[chanpos]);
1541                 ast_mutex_lock(&pri->lock);
1542         }
1543 }
1544
1545 #if defined(HAVE_PRI_CCSS)
1546 /*!
1547  * \internal
1548  * \brief Compare the CC agent private data by libpri cc_id.
1549  * \since 1.8
1550  *
1551  * \param obj pointer to the (user-defined part) of an object.
1552  * \param arg callback argument from ao2_callback()
1553  * \param flags flags from ao2_callback()
1554  *
1555  * \return values are a combination of enum _cb_results.
1556  */
1557 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
1558 {
1559         struct ast_cc_agent *agent_1 = obj;
1560         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
1561         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
1562
1563         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
1564                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
1565 }
1566 #endif  /* defined(HAVE_PRI_CCSS) */
1567
1568 #if defined(HAVE_PRI_CCSS)
1569 /*!
1570  * \internal
1571  * \brief Find the CC agent by libpri cc_id.
1572  * \since 1.8
1573  *
1574  * \param pri sig_pri PRI control structure.
1575  * \param cc_id CC record ID to find.
1576  *
1577  * \note
1578  * Since agents are refcounted, and this function returns
1579  * a reference to the agent, it is imperative that you decrement
1580  * the refcount of the agent once you have finished using it.
1581  *
1582  * \retval agent on success.
1583  * \retval NULL not found.
1584  */
1585 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_pri *pri, long cc_id)
1586 {
1587         struct sig_pri_cc_agent_prv finder = {
1588                 .pri = pri,
1589                 .cc_id = cc_id,
1590         };
1591
1592         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
1593                 sig_pri_cc_type_name);
1594 }
1595 #endif  /* defined(HAVE_PRI_CCSS) */
1596
1597 #if defined(HAVE_PRI_CCSS)
1598 /*!
1599  * \internal
1600  * \brief Compare the CC monitor instance by libpri cc_id.
1601  * \since 1.8
1602  *
1603  * \param obj pointer to the (user-defined part) of an object.
1604  * \param arg callback argument from ao2_callback()
1605  * \param flags flags from ao2_callback()
1606  *
1607  * \return values are a combination of enum _cb_results.
1608  */
1609 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
1610 {
1611         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
1612         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
1613
1614         return (monitor_1->pri == monitor_2->pri
1615                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
1616 }
1617 #endif  /* defined(HAVE_PRI_CCSS) */
1618
1619 #if defined(HAVE_PRI_CCSS)
1620 /*!
1621  * \internal
1622  * \brief Find the CC monitor instance by libpri cc_id.
1623  * \since 1.8
1624  *
1625  * \param pri sig_pri PRI control structure.
1626  * \param cc_id CC record ID to find.
1627  *
1628  * \note
1629  * Since monitor_instances are refcounted, and this function returns
1630  * a reference to the instance, it is imperative that you decrement
1631  * the refcount of the instance once you have finished using it.
1632  *
1633  * \retval monitor_instance on success.
1634  * \retval NULL not found.
1635  */
1636 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_pri *pri, long cc_id)
1637 {
1638         struct sig_pri_cc_monitor_instance finder = {
1639                 .pri = pri,
1640                 .cc_id = cc_id,
1641         };
1642
1643         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
1644 }
1645 #endif  /* defined(HAVE_PRI_CCSS) */
1646
1647 #if defined(HAVE_PRI_CCSS)
1648 /*!
1649  * \internal
1650  * \brief Destroy the given monitor instance.
1651  * \since 1.8
1652  *
1653  * \param data Monitor instance to destroy.
1654  *
1655  * \return Nothing
1656  */
1657 static void sig_pri_cc_monitor_instance_destroy(void *data)
1658 {
1659         struct sig_pri_cc_monitor_instance *monitor_instance = data;
1660
1661         if (monitor_instance->cc_id != -1) {
1662                 ast_mutex_lock(&monitor_instance->pri->lock);
1663                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
1664                 ast_mutex_unlock(&monitor_instance->pri->lock);
1665         }
1666         monitor_instance->pri->calls->module_unref();
1667 }
1668 #endif  /* defined(HAVE_PRI_CCSS) */
1669
1670 #if defined(HAVE_PRI_CCSS)
1671 /*!
1672  * \internal
1673  * \brief Construct a new monitor instance.
1674  * \since 1.8
1675  *
1676  * \param core_id CC core ID.
1677  * \param pri sig_pri PRI control structure.
1678  * \param cc_id CC record ID.
1679  * \param device_name Name of device (Asterisk channel name less sequence number).
1680  *
1681  * \note
1682  * Since monitor_instances are refcounted, and this function returns
1683  * a reference to the instance, it is imperative that you decrement
1684  * the refcount of the instance once you have finished using it.
1685  *
1686  * \retval monitor_instance on success.
1687  * \retval NULL on error.
1688  */
1689 static struct sig_pri_cc_monitor_instance *sig_pri_cc_monitor_instance_init(int core_id, struct sig_pri_pri *pri, long cc_id, const char *device_name)
1690 {
1691         struct sig_pri_cc_monitor_instance *monitor_instance;
1692
1693         if (!pri->calls->module_ref || !pri->calls->module_unref) {
1694                 return NULL;
1695         }
1696
1697         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
1698                 sig_pri_cc_monitor_instance_destroy);
1699         if (!monitor_instance) {
1700                 return NULL;
1701         }
1702
1703         monitor_instance->cc_id = cc_id;
1704         monitor_instance->pri = pri;
1705         monitor_instance->core_id = core_id;
1706         strcpy(monitor_instance->name, device_name);
1707
1708         pri->calls->module_ref();
1709
1710         ao2_link(sig_pri_cc_monitors, monitor_instance);
1711         return monitor_instance;
1712 }
1713 #endif  /* defined(HAVE_PRI_CCSS) */
1714
1715 #if defined(HAVE_PRI_CCSS)
1716 /*!
1717  * \internal
1718  * \brief Announce to the CC core that protocol CC monitor is available for this call.
1719  * \since 1.8
1720  *
1721  * \param pri sig_pri PRI control structure.
1722  * \param chanpos Channel position in the span.
1723  * \param cc_id CC record ID.
1724  * \param service CCBS/CCNR indication.
1725  *
1726  * \note Assumes the pri->lock is already obtained.
1727  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1728  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
1729  *
1730  * \retval 0 on success.
1731  * \retval -1 on error.
1732  */
1733 static int sig_pri_cc_available(struct sig_pri_pri *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
1734 {
1735         struct sig_pri_chan *pvt;
1736         struct ast_cc_config_params *cc_params;
1737         struct sig_pri_cc_monitor_instance *monitor;
1738         enum ast_cc_monitor_policies monitor_policy;
1739         int core_id;
1740         int res;
1741         char device_name[AST_CHANNEL_NAME];
1742         char dialstring[AST_CHANNEL_NAME];
1743
1744         pvt = pri->pvts[chanpos];
1745
1746         core_id = ast_cc_get_current_core_id(pvt->owner);
1747         if (core_id == -1) {
1748                 return -1;
1749         }
1750
1751         cc_params = ast_channel_get_cc_config_params(pvt->owner);
1752         if (!cc_params) {
1753                 return -1;
1754         }
1755
1756         res = -1;
1757         monitor_policy = ast_get_cc_monitor_policy(cc_params);
1758         switch (monitor_policy) {
1759         case AST_CC_MONITOR_NEVER:
1760                 /* CCSS is not enabled. */
1761                 break;
1762         case AST_CC_MONITOR_NATIVE:
1763         case AST_CC_MONITOR_ALWAYS:
1764                 /*
1765                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
1766                  * later in the call to sig_pri_cc_generic_check().
1767                  */
1768                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
1769                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
1770                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
1771                 if (!monitor) {
1772                         break;
1773                 }
1774                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
1775                         monitor);
1776                 if (res) {
1777                         monitor->cc_id = -1;
1778                         ao2_unlink(sig_pri_cc_monitors, monitor);
1779                         ao2_ref(monitor, -1);
1780                 }
1781                 break;
1782         case AST_CC_MONITOR_GENERIC:
1783                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
1784                         sig_pri_get_orig_dialstring(pvt), service, NULL);
1785                 /* Say it failed to force caller to cancel native CC. */
1786                 break;
1787         }
1788         return res;
1789 }
1790 #endif  /* defined(HAVE_PRI_CCSS) */
1791
1792 /*!
1793  * \internal
1794  * \brief Check if generic CC monitor is needed and request it.
1795  * \since 1.8
1796  *
1797  * \param pri sig_pri PRI control structure.
1798  * \param chanpos Channel position in the span.
1799  * \param service CCBS/CCNR indication.
1800  *
1801  * \note Assumes the pri->lock is already obtained.
1802  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1803  *
1804  * \return Nothing
1805  */
1806 static void sig_pri_cc_generic_check(struct sig_pri_pri *pri, int chanpos, enum ast_cc_service_type service)
1807 {
1808         struct ast_channel *owner;
1809         struct ast_cc_config_params *cc_params;
1810 #if defined(HAVE_PRI_CCSS)
1811         struct ast_cc_monitor *monitor;
1812         char device_name[AST_CHANNEL_NAME];
1813 #endif  /* defined(HAVE_PRI_CCSS) */
1814         enum ast_cc_monitor_policies monitor_policy;
1815         int core_id;
1816
1817         if (!pri->pvts[chanpos]->outgoing) {
1818                 /* This is not an outgoing call so it cannot be CC monitor. */
1819                 return;
1820         }
1821
1822         sig_pri_lock_owner(pri, chanpos);
1823         owner = pri->pvts[chanpos]->owner;
1824         if (!owner) {
1825                 return;
1826         }
1827         core_id = ast_cc_get_current_core_id(owner);
1828         if (core_id == -1) {
1829                 /* No CC core setup */
1830                 goto done;
1831         }
1832
1833         cc_params = ast_channel_get_cc_config_params(owner);
1834         if (!cc_params) {
1835                 /* Could not get CC config parameters. */
1836                 goto done;
1837         }
1838
1839 #if defined(HAVE_PRI_CCSS)
1840         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
1841         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
1842         if (monitor) {
1843                 /* CC monitor is already present so no need for generic CC. */
1844                 ao2_ref(monitor, -1);
1845                 goto done;
1846         }
1847 #endif  /* defined(HAVE_PRI_CCSS) */
1848
1849         monitor_policy = ast_get_cc_monitor_policy(cc_params);
1850         switch (monitor_policy) {
1851         case AST_CC_MONITOR_NEVER:
1852                 /* CCSS is not enabled. */
1853                 break;
1854         case AST_CC_MONITOR_NATIVE:
1855                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
1856                         /* Request generic CC monitor. */
1857                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
1858                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
1859                 }
1860                 break;
1861         case AST_CC_MONITOR_ALWAYS:
1862                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
1863                         /*
1864                          * Cannot monitor PTMP TE side since this is not defined.
1865                          * We are playing the roll of a phone in this case and
1866                          * a phone cannot monitor a party over the network without
1867                          * protocol help.
1868                          */
1869                         break;
1870                 }
1871                 /*
1872                  * We are either falling back or this is a PTMP NT span.
1873                  * Request generic CC monitor.
1874                  */
1875                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
1876                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
1877                 break;
1878         case AST_CC_MONITOR_GENERIC:
1879                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
1880                         /* Request generic CC monitor. */
1881                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
1882                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
1883                 }
1884                 break;
1885         }
1886
1887 done:
1888         ast_channel_unlock(owner);
1889 }
1890
1891 #if defined(HAVE_PRI_CCSS)
1892 /*!
1893  * \internal
1894  * \brief The CC link canceled the CC instance.
1895  * \since 1.8
1896  *
1897  * \param pri sig_pri PRI control structure.
1898  * \param cc_id CC record ID.
1899  * \param is_agent TRUE if the cc_id is for an agent.
1900  *
1901  * \return Nothing
1902  */
1903 static void sig_pri_cc_link_canceled(struct sig_pri_pri *pri, long cc_id, int is_agent)
1904 {
1905         if (is_agent) {
1906                 struct ast_cc_agent *agent;
1907
1908                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
1909                 if (!agent) {
1910                         return;
1911                 }
1912                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
1913                         sig_pri_cc_type_name);
1914                 ao2_ref(agent, -1);
1915         } else {
1916                 struct sig_pri_cc_monitor_instance *monitor;
1917
1918                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
1919                 if (!monitor) {
1920                         return;
1921                 }
1922                 monitor->cc_id = -1;
1923                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
1924                         "%s monitor got canceled by link", sig_pri_cc_type_name);
1925                 ao2_ref(monitor, -1);
1926         }
1927 }
1928 #endif  /* defined(HAVE_PRI_CCSS) */
1929
1930 /*!
1931  * \internal
1932  * \brief TRUE if PRI event came in on a CIS call.
1933  * \since 1.8
1934  *
1935  * \param channel PRI encoded span/channel
1936  *
1937  * \retval non-zero if CIS call.
1938  */
1939 static int sig_pri_is_cis_call(int channel)
1940 {
1941         return channel != -1 && (channel & PRI_CIS_CALL);
1942 }
1943
1944 /*!
1945  * \internal
1946  * \brief Handle the CIS associated PRI subcommand events.
1947  * \since 1.8
1948  *
1949  * \param pri sig_pri PRI control structure.
1950  * \param event_id PRI event id
1951  * \param subcmds Subcommands to process if any. (Could be NULL).
1952  * \param call_rsp libpri opaque call structure to send any responses toward.
1953  * Could be NULL either because it is not available or the call is for the
1954  * dummy call reference.  However, this should not be NULL in the cases that
1955  * need to use the pointer to send a response message back.
1956  *
1957  * \note Assumes the pri->lock is already obtained.
1958  *
1959  * \return Nothing
1960  */
1961 static void sig_pri_handle_cis_subcmds(struct sig_pri_pri *pri, int event_id,
1962         const struct pri_subcommands *subcmds, q931_call *call_rsp)
1963 {
1964         int index;
1965 #if defined(HAVE_PRI_CCSS)
1966         struct ast_cc_agent *agent;
1967         struct sig_pri_cc_agent_prv *agent_prv;
1968         struct sig_pri_cc_monitor_instance *monitor;
1969 #endif  /* defined(HAVE_PRI_CCSS) */
1970
1971         if (!subcmds) {
1972                 return;
1973         }
1974         for (index = 0; index < subcmds->counter_subcmd; ++index) {
1975                 const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
1976
1977                 switch (subcmd->cmd) {
1978 #if defined(STATUS_REQUEST_PLACE_HOLDER)
1979                 case PRI_SUBCMD_STATUS_REQ:
1980                 case PRI_SUBCMD_STATUS_REQ_RSP:
1981                         /* Ignore for now. */
1982                         break;
1983 #endif  /* defined(STATUS_REQUEST_PLACE_HOLDER) */
1984 #if defined(HAVE_PRI_CCSS)
1985                 case PRI_SUBCMD_CC_REQ:
1986                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_request.cc_id);
1987                         if (!agent) {
1988                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
1989                                 break;
1990                         }
1991                         if (!ast_cc_request_is_within_limits()) {
1992                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
1993                                         5/* queue_full */)) {
1994                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
1995                                 }
1996                                 ast_cc_failed(agent->core_id, "%s agent system CC queue full",
1997                                         sig_pri_cc_type_name);
1998                                 ao2_ref(agent, -1);
1999                                 break;
2000                         }
2001                         agent_prv = agent->private_data;
2002                         agent_prv->cc_request_response_pending = 1;
2003                         if (ast_cc_agent_accept_request(agent->core_id,
2004                                 "%s caller accepted CC offer.", sig_pri_cc_type_name)) {
2005                                 agent_prv->cc_request_response_pending = 0;
2006                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
2007                                         2/* short_term_denial */)) {
2008                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
2009                                 }
2010                                 ast_cc_failed(agent->core_id, "%s agent CC core request accept failed",
2011                                         sig_pri_cc_type_name);
2012                         }
2013                         ao2_ref(agent, -1);
2014                         break;
2015 #endif  /* defined(HAVE_PRI_CCSS) */
2016 #if defined(HAVE_PRI_CCSS)
2017                 case PRI_SUBCMD_CC_REQ_RSP:
2018                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2019                                 subcmd->u.cc_request_rsp.cc_id);
2020                         if (!monitor) {
2021                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request_rsp.cc_id);
2022                                 break;
2023                         }
2024                         switch (subcmd->u.cc_request_rsp.status) {
2025                         case 0:/* success */
2026                                 ast_cc_monitor_request_acked(monitor->core_id,
2027                                         "%s far end accepted CC request", sig_pri_cc_type_name);
2028                                 break;
2029                         case 1:/* timeout */
2030                                 ast_verb(2, "core_id:%d %s CC request timeout\n", monitor->core_id,
2031                                         sig_pri_cc_type_name);
2032                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2033                                         "%s CC request timeout", sig_pri_cc_type_name);
2034                                 break;
2035                         case 2:/* error */
2036                                 ast_verb(2, "core_id:%d %s CC request error: %s\n", monitor->core_id,
2037                                         sig_pri_cc_type_name,
2038                                         pri_facility_error2str(subcmd->u.cc_request_rsp.fail_code));
2039                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2040                                         "%s CC request error", sig_pri_cc_type_name);
2041                                 break;
2042                         case 3:/* reject */
2043                                 ast_verb(2, "core_id:%d %s CC request reject: %s\n", monitor->core_id,
2044                                         sig_pri_cc_type_name,
2045                                         pri_facility_reject2str(subcmd->u.cc_request_rsp.fail_code));
2046                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2047                                         "%s CC request reject", sig_pri_cc_type_name);
2048                                 break;
2049                         default:
2050                                 ast_verb(2, "core_id:%d %s CC request unknown status %d\n",
2051                                         monitor->core_id, sig_pri_cc_type_name,
2052                                         subcmd->u.cc_request_rsp.status);
2053                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2054                                         "%s CC request unknown status", sig_pri_cc_type_name);
2055                                 break;
2056                         }
2057                         ao2_ref(monitor, -1);
2058                         break;
2059 #endif  /* defined(HAVE_PRI_CCSS) */
2060 #if defined(HAVE_PRI_CCSS)
2061                 case PRI_SUBCMD_CC_REMOTE_USER_FREE:
2062                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2063                                 subcmd->u.cc_remote_user_free.cc_id);
2064                         if (!monitor) {
2065                                 pri_cc_cancel(pri->pri, subcmd->u.cc_remote_user_free.cc_id);
2066                                 break;
2067                         }
2068                         ast_cc_monitor_callee_available(monitor->core_id,
2069                                 "%s callee has become available", sig_pri_cc_type_name);
2070                         ao2_ref(monitor, -1);
2071                         break;
2072 #endif  /* defined(HAVE_PRI_CCSS) */
2073 #if defined(HAVE_PRI_CCSS)
2074                 case PRI_SUBCMD_CC_B_FREE:
2075                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2076                                 subcmd->u.cc_b_free.cc_id);
2077                         if (!monitor) {
2078                                 pri_cc_cancel(pri->pri, subcmd->u.cc_b_free.cc_id);
2079                                 break;
2080                         }
2081                         ast_cc_monitor_party_b_free(monitor->core_id);
2082                         ao2_ref(monitor, -1);
2083                         break;
2084 #endif  /* defined(HAVE_PRI_CCSS) */
2085 #if defined(HAVE_PRI_CCSS)
2086                 case PRI_SUBCMD_CC_STATUS_REQ:
2087                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2088                                 subcmd->u.cc_status_req.cc_id);
2089                         if (!monitor) {
2090                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status_req.cc_id);
2091                                 break;
2092                         }
2093                         ast_cc_monitor_status_request(monitor->core_id);
2094                         ao2_ref(monitor, -1);
2095                         break;
2096 #endif  /* defined(HAVE_PRI_CCSS) */
2097 #if defined(HAVE_PRI_CCSS)
2098                 case PRI_SUBCMD_CC_STATUS_REQ_RSP:
2099                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status_req_rsp.cc_id);
2100                         if (!agent) {
2101                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status_req_rsp.cc_id);
2102                                 break;
2103                         }
2104                         ast_cc_agent_status_response(agent->core_id,
2105                                 subcmd->u.cc_status_req_rsp.status ? AST_DEVICE_INUSE
2106                                 : AST_DEVICE_NOT_INUSE);
2107                         ao2_ref(agent, -1);
2108                         break;
2109 #endif  /* defined(HAVE_PRI_CCSS) */
2110 #if defined(HAVE_PRI_CCSS)
2111                 case PRI_SUBCMD_CC_STATUS:
2112                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status.cc_id);
2113                         if (!agent) {
2114                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status.cc_id);
2115                                 break;
2116                         }
2117                         if (subcmd->u.cc_status.status) {
2118                                 ast_cc_agent_caller_busy(agent->core_id, "%s agent caller is busy",
2119                                         sig_pri_cc_type_name);
2120                         } else {
2121                                 ast_cc_agent_caller_available(agent->core_id,
2122                                         "%s agent caller is available", sig_pri_cc_type_name);
2123                         }
2124                         ao2_ref(agent, -1);
2125                         break;
2126 #endif  /* defined(HAVE_PRI_CCSS) */
2127 #if defined(HAVE_PRI_CCSS)
2128                 case PRI_SUBCMD_CC_CANCEL:
2129                         sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
2130                                 subcmd->u.cc_cancel.is_agent);
2131                         break;
2132 #endif  /* defined(HAVE_PRI_CCSS) */
2133 #if defined(HAVE_PRI_CCSS)
2134                 case PRI_SUBCMD_CC_STOP_ALERTING:
2135                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2136                                 subcmd->u.cc_stop_alerting.cc_id);
2137                         if (!monitor) {
2138                                 pri_cc_cancel(pri->pri, subcmd->u.cc_stop_alerting.cc_id);
2139                                 break;
2140                         }
2141                         ast_cc_monitor_stop_ringing(monitor->core_id);
2142                         ao2_ref(monitor, -1);
2143                         break;
2144 #endif  /* defined(HAVE_PRI_CCSS) */
2145                 default:
2146                         ast_debug(2,
2147                                 "Unknown CIS subcommand(%d) in %s event on span %d.\n",
2148                                 subcmd->cmd, pri_event2str(event_id), pri->span);
2149                         break;
2150                 }
2151         }
2152 }
2153
2154 /*!
2155  * \internal
2156  * \brief Handle the call associated PRI subcommand events.
2157  * \since 1.8
2158  *
2159  * \param pri sig_pri PRI control structure.
2160  * \param chanpos Channel position in the span.
2161  * \param event_id PRI event id
2162  * \param channel PRI encoded span/channel
2163  * \param subcmds Subcommands to process if any. (Could be NULL).
2164  * \param call_rsp libpri opaque call structure to send any responses toward.
2165  * Could be NULL either because it is not available or the call is for the
2166  * dummy call reference.  However, this should not be NULL in the cases that
2167  * need to use the pointer to send a response message back.
2168  *
2169  * \note Assumes the pri->lock is already obtained.
2170  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2171  *
2172  * \return Nothing
2173  */
2174 static void sig_pri_handle_subcmds(struct sig_pri_pri *pri, int chanpos, int event_id,
2175         int channel, const struct pri_subcommands *subcmds, q931_call *call_rsp)
2176 {
2177         int index;
2178         struct ast_channel *owner;
2179         struct ast_party_redirecting ast_redirecting;
2180
2181         if (!subcmds) {
2182                 return;
2183         }
2184         for (index = 0; index < subcmds->counter_subcmd; ++index) {
2185                 const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
2186
2187                 switch (subcmd->cmd) {
2188                 case PRI_SUBCMD_CONNECTED_LINE:
2189                         sig_pri_lock_owner(pri, chanpos);
2190                         owner = pri->pvts[chanpos]->owner;
2191                         if (owner) {
2192                                 struct ast_party_connected_line ast_connected;
2193                                 int caller_id_update;
2194
2195                                 /* Extract the connected line information */
2196                                 ast_party_connected_line_init(&ast_connected);
2197                                 sig_pri_party_id_convert(&ast_connected.id, &subcmd->u.connected_line.id,
2198                                         pri);
2199
2200                                 caller_id_update = 0;
2201                                 if (ast_connected.id.name) {
2202                                         /* Save name for Caller-ID update */
2203                                         ast_copy_string(pri->pvts[chanpos]->cid_name,
2204                                                 ast_connected.id.name, sizeof(pri->pvts[chanpos]->cid_name));
2205                                         caller_id_update = 1;
2206                                 }
2207                                 if (ast_connected.id.number) {
2208                                         /* Save number for Caller-ID update */
2209                                         ast_copy_string(pri->pvts[chanpos]->cid_num, ast_connected.id.number,
2210                                                 sizeof(pri->pvts[chanpos]->cid_num));
2211                                         pri->pvts[chanpos]->cid_ton = ast_connected.id.number_type;
2212                                         caller_id_update = 1;
2213                                 } else {
2214                                         ast_connected.id.number = ast_strdup("");
2215                                 }
2216                                 ast_connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
2217
2218                                 pri->pvts[chanpos]->cid_subaddr[0] = '\0';
2219 #if defined(HAVE_PRI_SUBADDR)
2220                                 if (ast_connected.id.subaddress.valid) {
2221                                         ast_party_subaddress_set(&owner->cid.subaddress,
2222                                                 &ast_connected.id.subaddress);
2223                                         if (ast_connected.id.subaddress.str) {
2224                                                 ast_copy_string(pri->pvts[chanpos]->cid_subaddr,
2225                                                         ast_connected.id.subaddress.str,
2226                                                         sizeof(pri->pvts[chanpos]->cid_subaddr));
2227                                         }
2228                                 }
2229 #endif  /* defined(HAVE_PRI_SUBADDR) */
2230                                 if (caller_id_update) {
2231                                         pri->pvts[chanpos]->callingpres =
2232                                                 ast_connected.id.number_presentation;
2233                                         sig_pri_set_caller_id(pri->pvts[chanpos]);
2234                                         ast_set_callerid(owner, S_OR(ast_connected.id.number, NULL),
2235                                                 S_OR(ast_connected.id.name, NULL),
2236                                                 S_OR(ast_connected.id.number, NULL));
2237                                 }
2238
2239                                 /* Update the connected line information on the other channel */
2240                                 if (event_id != PRI_EVENT_RING) {
2241                                         /* This connected_line update was not from a SETUP message. */
2242                                         ast_channel_queue_connected_line_update(owner, &ast_connected);
2243                                 }
2244
2245                                 ast_party_connected_line_free(&ast_connected);
2246                                 ast_channel_unlock(owner);
2247                         }
2248                         break;
2249                 case PRI_SUBCMD_REDIRECTING:
2250                         sig_pri_lock_owner(pri, chanpos);
2251                         owner = pri->pvts[chanpos]->owner;
2252                         if (owner) {
2253                                 sig_pri_redirecting_convert(&ast_redirecting, &subcmd->u.redirecting,
2254                                         &owner->redirecting, pri);
2255
2256 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
2257
2258                                 ast_channel_set_redirecting(owner, &ast_redirecting);
2259                                 if (event_id != PRI_EVENT_RING) {
2260                                         /* This redirection was not from a SETUP message. */
2261                                         ast_channel_queue_redirecting_update(owner, &ast_redirecting);
2262                                 }
2263                                 ast_party_redirecting_free(&ast_redirecting);
2264
2265                                 ast_channel_unlock(owner);
2266                         }
2267                         break;
2268 #if defined(HAVE_PRI_CALL_REROUTING)
2269                 case PRI_SUBCMD_REROUTING:
2270                         sig_pri_lock_owner(pri, chanpos);
2271                         owner = pri->pvts[chanpos]->owner;
2272                         if (owner) {
2273                                 struct pri_party_redirecting pri_deflection;
2274
2275                                 if (!call_rsp) {
2276                                         ast_channel_unlock(owner);
2277                                         ast_log(LOG_WARNING,
2278                                                 "CallRerouting/CallDeflection to '%s' without call!\n",
2279                                                 subcmd->u.rerouting.deflection.to.number.str);
2280                                         break;
2281                                 }
2282
2283                                 pri_deflection = subcmd->u.rerouting.deflection;
2284
2285                                 ast_string_field_set(owner, call_forward, pri_deflection.to.number.str);
2286
2287                                 /* Adjust the deflecting to number based upon the subscription option. */
2288                                 switch (subcmd->u.rerouting.subscription_option) {
2289                                 case 0: /* noNotification */
2290                                 case 1: /* notificationWithoutDivertedToNr */
2291                                         /* Delete the number because the far end is not supposed to see it. */
2292                                         pri_deflection.to.number.presentation =
2293                                                 PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
2294                                         pri_deflection.to.number.plan =
2295                                                 (PRI_TON_UNKNOWN << 4) | PRI_NPI_E163_E164;
2296                                         pri_deflection.to.number.str[0] = '\0';
2297                                         break;
2298                                 case 2: /* notificationWithDivertedToNr */
2299                                         break;
2300                                 case 3: /* notApplicable */
2301                                 default:
2302                                         break;
2303                                 }
2304                                 sig_pri_redirecting_convert(&ast_redirecting, &pri_deflection,
2305                                         &owner->redirecting, pri);
2306                                 ast_channel_set_redirecting(owner, &ast_redirecting);
2307                                 ast_party_redirecting_free(&ast_redirecting);
2308
2309                                 /*
2310                                  * Send back positive ACK to CallRerouting/CallDeflection.
2311                                  *
2312                                  * Note:  This call will be hungup by the dial application when
2313                                  * it processes the call_forward string set above.
2314                                  */
2315                                 pri_rerouting_rsp(pri->pri, call_rsp, subcmd->u.rerouting.invoke_id,
2316                                         PRI_REROUTING_RSP_OK_CLEAR);
2317
2318                                 /* This line is BUSY to further attempts by this dialing attempt. */
2319                                 ast_queue_control(owner, AST_CONTROL_BUSY);
2320
2321                                 ast_channel_unlock(owner);
2322                         }
2323                         break;
2324 #endif  /* defined(HAVE_PRI_CALL_REROUTING) */
2325 #if defined(HAVE_PRI_CCSS)
2326                 case PRI_SUBCMD_CC_AVAILABLE:
2327                         sig_pri_lock_owner(pri, chanpos);
2328                         owner = pri->pvts[chanpos]->owner;
2329                         if (owner) {
2330                                 enum ast_cc_service_type service;
2331
2332                                 switch (event_id) {
2333                                 case PRI_EVENT_RINGING:
2334                                         service = AST_CC_CCNR;
2335                                         break;
2336                                 case PRI_EVENT_HANGUP_REQ:
2337                                         /* We will assume that the cause was busy/congestion. */
2338                                         service = AST_CC_CCBS;
2339                                         break;
2340                                 default:
2341                                         service = AST_CC_NONE;
2342                                         break;
2343                                 }
2344                                 if (service == AST_CC_NONE
2345                                         || sig_pri_cc_available(pri, chanpos, subcmd->u.cc_available.cc_id,
2346                                         service)) {
2347                                         pri_cc_cancel(pri->pri, subcmd->u.cc_available.cc_id);
2348                                 }
2349                                 ast_channel_unlock(owner);
2350                         } else {
2351                                 /* No asterisk channel. */
2352                                 pri_cc_cancel(pri->pri, subcmd->u.cc_available.cc_id);
2353                         }
2354                         break;
2355 #endif  /* defined(HAVE_PRI_CCSS) */
2356 #if defined(HAVE_PRI_CCSS)
2357                 case PRI_SUBCMD_CC_CALL:
2358                         sig_pri_lock_owner(pri, chanpos);
2359                         owner = pri->pvts[chanpos]->owner;
2360                         if (owner) {
2361                                 struct ast_cc_agent *agent;
2362
2363                                 agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_call.cc_id);
2364                                 if (agent) {
2365                                         ast_setup_cc_recall_datastore(owner, agent->core_id);
2366                                         ast_cc_agent_set_interfaces_chanvar(owner);
2367                                         ast_cc_agent_recalling(agent->core_id,
2368                                                 "%s caller is attempting recall", sig_pri_cc_type_name);
2369                                         ao2_ref(agent, -1);
2370                                 }
2371
2372                                 ast_channel_unlock(owner);
2373                         }
2374                         break;
2375 #endif  /* defined(HAVE_PRI_CCSS) */
2376 #if defined(HAVE_PRI_CCSS)
2377                 case PRI_SUBCMD_CC_CANCEL:
2378                         sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
2379                                 subcmd->u.cc_cancel.is_agent);
2380                         break;
2381 #endif  /* defined(HAVE_PRI_CCSS) */
2382                 default:
2383                         ast_debug(2,
2384                                 "Unknown call subcommand(%d) in %s event on channel %d/%d on span %d.\n",
2385                                 subcmd->cmd, pri_event2str(event_id), PRI_SPAN(channel),
2386                                 PRI_CHANNEL(channel), pri->span);
2387                         break;
2388                 }
2389         }
2390 }
2391
2392 #if defined(HAVE_PRI_CALL_HOLD)
2393 /*!
2394  * \internal
2395  * \brief Attempt to transfer the active call to the held call.
2396  * \since 1.8
2397  *
2398  * \param pri sig_pri PRI control structure.
2399  * \param active_call Active call to transfer.
2400  * \param held_call Held call to transfer.
2401  *
2402  * \note Assumes the pri->lock is already obtained.
2403  *
2404  * \retval 0 on success.
2405  * \retval -1 on error.
2406  */
2407 static int sig_pri_attempt_transfer(struct sig_pri_pri *pri, q931_call *active_call, q931_call *held_call)
2408 {
2409         int retval;
2410         int active_chanpos;
2411         int held_chanpos;
2412         struct ast_channel *active_ast;
2413         struct ast_channel *held_ast;
2414         struct ast_channel *bridged;
2415
2416         active_chanpos = pri_find_pri_call(pri, active_call);
2417         held_chanpos = pri_find_pri_call(pri, held_call);
2418         if (active_chanpos < 0 || held_chanpos < 0) {
2419                 return -1;
2420         }
2421
2422         sig_pri_lock_private(pri->pvts[active_chanpos]);
2423         sig_pri_lock_private(pri->pvts[held_chanpos]);
2424         sig_pri_lock_owner(pri, active_chanpos);
2425         sig_pri_lock_owner(pri, held_chanpos);
2426
2427         active_ast = pri->pvts[active_chanpos]->owner;
2428         held_ast = pri->pvts[held_chanpos]->owner;
2429         if (!active_ast || !held_ast) {
2430                 if (active_ast) {
2431                         ast_channel_unlock(active_ast);
2432                 }
2433                 if (held_ast) {
2434                         ast_channel_unlock(held_ast);
2435                 }
2436                 sig_pri_unlock_private(pri->pvts[active_chanpos]);
2437                 sig_pri_unlock_private(pri->pvts[held_chanpos]);
2438                 return -1;
2439         }
2440
2441         bridged = ast_bridged_channel(held_ast);
2442         if (bridged) {
2443                 ast_queue_control(held_ast, AST_CONTROL_UNHOLD);
2444
2445                 ast_verb(3, "TRANSFERRING %s to %s\n", held_ast->name, active_ast->name);
2446                 retval = ast_channel_masquerade(active_ast, bridged);
2447         } else {
2448                 /*
2449                  * Could not transfer.  Held channel is not bridged anymore.
2450                  * Held party probably got tired of waiting and hung up.
2451                  */
2452                 retval = -1;
2453         }
2454
2455         ast_channel_unlock(active_ast);
2456         ast_channel_unlock(held_ast);
2457         sig_pri_unlock_private(pri->pvts[active_chanpos]);
2458         sig_pri_unlock_private(pri->pvts[held_chanpos]);
2459
2460         return retval;
2461 }
2462 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
2463
2464 #if defined(HAVE_PRI_CALL_HOLD)
2465 /*!
2466  * \internal
2467  * \brief Handle the hold event from libpri.
2468  * \since 1.8
2469  *
2470  * \param pri sig_pri PRI control structure.
2471  * \param ev Hold event received.
2472  *
2473  * \note Assumes the pri->lock is already obtained.
2474  *
2475  * \retval 0 on success.
2476  * \retval -1 on error.
2477  */
2478 static int sig_pri_handle_hold(struct sig_pri_pri *pri, pri_event *ev)
2479 {
2480         int retval;
2481         int chanpos_old;
2482         int chanpos_new;
2483         struct ast_channel *bridged;
2484         struct ast_channel *owner;
2485
2486         chanpos_old = pri_find_principle(pri, ev->hold.channel, ev->hold.call);
2487         if (chanpos_old < 0) {
2488                 ast_log(LOG_WARNING,
2489                         "Received HOLD on unconfigured channel %d/%d span %d\n",
2490                         PRI_SPAN(ev->hold.channel), PRI_CHANNEL(ev->hold.channel), pri->span);
2491                 return -1;
2492         }
2493         if (pri->pvts[chanpos_old]->no_b_channel) {
2494                 /* Call is already on hold or is call waiting call. */
2495                 return -1;
2496         }
2497
2498         sig_pri_lock_private(pri->pvts[chanpos_old]);
2499         sig_pri_lock_owner(pri, chanpos_old);
2500         owner = pri->pvts[chanpos_old]->owner;
2501         if (!owner) {
2502                 retval = -1;
2503                 goto done_with_private;
2504         }
2505         bridged = ast_bridged_channel(owner);
2506         if (!bridged) {
2507                 /* Cannot hold a call that is not bridged. */
2508                 retval = -1;
2509                 goto done_with_owner;
2510         }
2511         chanpos_new = pri_find_empty_nobch(pri);
2512         if (chanpos_new < 0) {
2513                 /* No hold channel available. */
2514                 retval = -1;
2515                 goto done_with_owner;
2516         }
2517         sig_pri_handle_subcmds(pri, chanpos_old, ev->e, ev->hold.channel, ev->hold.subcmds,
2518                 ev->hold.call);
2519         chanpos_new = pri_fixup_principle(pri, chanpos_new, ev->hold.call);
2520         if (chanpos_new < 0) {
2521                 /* Should never happen. */
2522                 retval = -1;
2523         } else {
2524                 struct ast_frame f = { AST_FRAME_CONTROL, };
2525
2526                 f.subclass.integer = AST_CONTROL_HOLD;
2527                 ast_queue_frame(owner, &f);
2528                 sig_pri_span_devstate_changed(pri);
2529                 retval = 0;
2530         }
2531
2532 done_with_owner:;
2533         ast_channel_unlock(owner);
2534 done_with_private:;
2535         sig_pri_unlock_private(pri->pvts[chanpos_old]);
2536
2537         return retval;
2538 }
2539 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
2540
2541 #if defined(HAVE_PRI_CALL_HOLD)
2542 /*!
2543  * \internal
2544  * \brief Handle the retrieve event from libpri.
2545  * \since 1.8
2546  *
2547  * \param pri sig_pri PRI control structure.
2548  * \param ev Retrieve event received.
2549  *
2550  * \note Assumes the pri->lock is already obtained.
2551  *
2552  * \return Nothing
2553  */
2554 static void sig_pri_handle_retrieve(struct sig_pri_pri *pri, pri_event *ev)
2555 {
2556         int chanpos;
2557
2558         if (!(ev->retrieve.channel & PRI_HELD_CALL)
2559                 || pri_find_principle(pri, ev->retrieve.channel, ev->retrieve.call) < 0) {
2560                 /* The call is not currently held. */
2561                 pri_retrieve_rej(pri->pri, ev->retrieve.call,
2562                         PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED);
2563                 return;
2564         }
2565         if (PRI_CHANNEL(ev->retrieve.channel) == 0xFF) {
2566                 chanpos = pri_find_empty_chan(pri, 1);
2567         } else {
2568                 chanpos = pri_find_principle(pri,
2569                         ev->retrieve.channel & ~PRI_HELD_CALL, ev->retrieve.call);
2570                 if (ev->retrieve.flexible
2571                         && (chanpos < 0 || pri->pvts[chanpos]->owner)) {
2572                         /*
2573                          * Channel selection is flexible and the requested channel
2574                          * is bad or already in use.  Pick another channel.
2575                          */
2576                         chanpos = pri_find_empty_chan(pri, 1);
2577                 }
2578         }
2579         if (chanpos < 0) {
2580                 pri_retrieve_rej(pri->pri, ev->retrieve.call,
2581                         ev->retrieve.flexible ? PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION
2582                         : PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
2583                 return;
2584         }
2585         chanpos = pri_fixup_principle(pri, chanpos, ev->retrieve.call);
2586         if (chanpos < 0) {
2587                 /* Channel is already in use. */
2588                 pri_retrieve_rej(pri->pri, ev->retrieve.call,
2589                         PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
2590                 return;
2591         }
2592         sig_pri_lock_private(pri->pvts[chanpos]);
2593         sig_pri_handle_subcmds(pri, chanpos, ev->e, ev->retrieve.channel,
2594                 ev->retrieve.subcmds, ev->retrieve.call);
2595         {
2596                 struct ast_frame f = { AST_FRAME_CONTROL, };
2597
2598                 f.subclass.integer = AST_CONTROL_UNHOLD;
2599                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
2600         }
2601         sig_pri_unlock_private(pri->pvts[chanpos]);
2602         sig_pri_span_devstate_changed(pri);
2603         pri_retrieve_ack(pri->pri, ev->retrieve.call,
2604                 PVT_TO_CHANNEL(pri->pvts[chanpos]));
2605 }
2606 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
2607
2608 static void *pri_dchannel(void *vpri)
2609 {
2610         struct sig_pri_pri *pri = vpri;
2611         pri_event *e;
2612         struct pollfd fds[SIG_PRI_NUM_DCHANS];
2613         int res;
2614         int chanpos = 0;
2615         int x;
2616         struct ast_channel *c;
2617         struct timeval tv, lowest, *next;
2618         int doidling=0;
2619         char *cc;
2620         time_t t;
2621         int i, which=-1;
2622         int numdchans;
2623         pthread_t threadid;
2624         char ani2str[6];
2625         char plancallingnum[AST_MAX_EXTENSION];
2626         char plancallingani[AST_MAX_EXTENSION];
2627         char calledtonstr[10];
2628         struct timeval lastidle = { 0, 0 };
2629         pthread_t p;
2630         struct ast_channel *idle;
2631         char idlen[80];
2632         int nextidle = -1;
2633         int haveidles;
2634         int activeidles;
2635
2636         gettimeofday(&lastidle, NULL);
2637         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
2638
2639         if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
2640                 /* Need to do idle dialing, check to be sure though */
2641                 cc = strchr(pri->idleext, '@');
2642                 if (cc) {
2643                         *cc = '\0';
2644                         cc++;
2645                         ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
2646 #if 0
2647                         /* Extensions may not be loaded yet */
2648                         if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
2649                                 ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
2650                         else
2651 #endif
2652                                 doidling = 1;
2653                 } else
2654                         ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
2655         }
2656         for (;;) {
2657                 for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
2658                         if (!pri->dchans[i])
2659                                 break;
2660                         fds[i].fd = pri->fds[i];
2661                         fds[i].events = POLLIN | POLLPRI;
2662                         fds[i].revents = 0;
2663                 }
2664                 numdchans = i;
2665                 time(&t);
2666                 ast_mutex_lock(&pri->lock);
2667                 if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->sig != SIG_BRI_PTMP) && (pri->resetinterval > 0)) {
2668                         if (pri->resetting && pri_is_up(pri)) {
2669                                 if (pri->resetpos < 0)
2670                                         pri_check_restart(pri);
2671                         } else {
2672                                 if (!pri->resetting     && (t - pri->lastreset) >= pri->resetinterval) {
2673                                         pri->resetting = 1;
2674                                         pri->resetpos = -1;
2675                                 }
2676                         }
2677                 }
2678                 /* Look for any idle channels if appropriate */
2679                 if (doidling && pri_is_up(pri)) {
2680                         nextidle = -1;
2681                         haveidles = 0;
2682                         activeidles = 0;
2683                         for (x = pri->numchans; x >= 0; x--) {
2684                                 if (pri->pvts[x]
2685                                         && !pri->pvts[x]->owner
2686                                         && !pri->pvts[x]->call
2687                                         && !pri->pvts[x]->no_b_channel) {
2688                                         if (haveidles < pri->minunused) {
2689                                                 haveidles++;
2690                                         } else if (!pri->pvts[x]->resetting) {
2691                                                 nextidle = x;
2692                                                 break;
2693                                         }
2694                                 } else if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall)
2695                                         activeidles++;
2696                         }
2697                         if (nextidle > -1) {
2698                                 if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
2699                                         /* Don't create a new idle call more than once per second */
2700                                         snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
2701                                         idle = sig_pri_request(pri->pvts[nextidle], AST_FORMAT_ULAW, NULL, 0);
2702                                         if (idle) {
2703                                                 pri->pvts[nextidle]->isidlecall = 1;
2704                                                 if (ast_pthread_create_background(&p, NULL, do_idle_thread, pri->pvts[nextidle])) {
2705                                                         ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
2706                                                         ast_hangup(idle);
2707                                                 }
2708                                         } else
2709                                                 ast_log(LOG_WARNING, "Unable to request channel 'DAHDI/%s' for idle call\n", idlen);
2710                                         gettimeofday(&lastidle, NULL);
2711                                 }
2712                         } else if ((haveidles < pri->minunused) &&
2713                                 (activeidles > pri->minidle)) {
2714                                 /* Mark something for hangup if there is something
2715                                    that can be hungup */
2716                                 for (x = pri->numchans; x >= 0; x--) {
2717                                         /* find a candidate channel */
2718                                         if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
2719                                                 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2720                                                 haveidles++;
2721                                                 /* Stop if we have enough idle channels or
2722                                                   can't spare any more active idle ones */
2723                                                 if ((haveidles >= pri->minunused) ||
2724                                                         (activeidles <= pri->minidle))
2725                                                         break;
2726                                         }
2727                                 }
2728                         }
2729                 }
2730                 /* Start with reasonable max */
2731                 lowest = ast_tv(60, 0);
2732                 for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
2733                         /* Find lowest available d-channel */
2734                         if (!pri->dchans[i])
2735                                 break;
2736                         if ((next = pri_schedule_next(pri->dchans[i]))) {
2737                                 /* We need relative time here */
2738                                 tv = ast_tvsub(*next, ast_tvnow());
2739                                 if (tv.tv_sec < 0) {
2740                                         tv = ast_tv(0,0);
2741                                 }
2742                                 if (doidling || pri->resetting) {
2743                                         if (tv.tv_sec > 1) {
2744                                                 tv = ast_tv(1, 0);
2745                                         }
2746                                 } else {
2747                                         if (tv.tv_sec > 60) {
2748                                                 tv = ast_tv(60, 0);
2749                                         }
2750                                 }
2751                         } else if (doidling || pri->resetting) {
2752                                 /* Make sure we stop at least once per second if we're
2753                                    monitoring idle channels */
2754                                 tv = ast_tv(1,0);
2755                         } else {
2756                                 /* Don't poll for more than 60 seconds */
2757                                 tv = ast_tv(60, 0);
2758                         }
2759                         if (!i || ast_tvcmp(tv, lowest) < 0) {
2760                                 lowest = tv;
2761                         }
2762                 }
2763                 ast_mutex_unlock(&pri->lock);
2764
2765                 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
2766                 pthread_testcancel();
2767                 e = NULL;
2768                 res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
2769                 pthread_testcancel();
2770                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
2771
2772                 ast_mutex_lock(&pri->lock);
2773                 if (!res) {
2774                         for (which = 0; which < SIG_PRI_NUM_DCHANS; which++) {
2775                                 if (!pri->dchans[which])
2776                                         break;
2777                                 /* Just a timeout, run the scheduler */
2778                                 e = pri_schedule_run(pri->dchans[which]);
2779                                 if (e)
2780                                         break;
2781                         }
2782                 } else if (res > -1) {
2783                         for (which = 0; which < SIG_PRI_NUM_DCHANS; which++) {
2784                                 if (!pri->dchans[which])
2785                                         break;
2786                                 if (fds[which].revents & POLLPRI) {
2787                                         sig_pri_handle_dchan_exception(pri, which);
2788                                 } else if (fds[which].revents & POLLIN) {
2789                                         e = pri_check_event(pri->dchans[which]);
2790                                 }
2791                                 if (e)
2792                                         break;
2793                         }
2794                 } else if (errno != EINTR)
2795                         ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
2796
2797                 if (e) {
2798                         if (pri->debug)
2799                                 pri_dump_event(pri->dchans[which], e);
2800
2801                         if (e->e != PRI_EVENT_DCHAN_DOWN) {
2802                                 if (!(pri->dchanavail[which] & DCHAN_UP)) {
2803                                         ast_verb(2, "%s D-Channel on span %d up\n", pri_order(which), pri->span);
2804                                 }
2805                                 pri->dchanavail[which] |= DCHAN_UP;
2806                         } else {
2807                                 if (pri->dchanavail[which] & DCHAN_UP) {
2808                                         ast_verb(2, "%s D-Channel on span %d down\n", pri_order(which), pri->span);
2809                                 }
2810                                 pri->dchanavail[which] &= ~DCHAN_UP;
2811                         }
2812
2813                         if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
2814                                 /* Must be an NFAS group that has the secondary dchan active */
2815                                 pri->pri = pri->dchans[which];
2816
2817                         switch (e->e) {
2818                         case PRI_EVENT_DCHAN_UP:
2819                                 if (!pri->pri) pri_find_dchan(pri);
2820
2821                                 /* Note presense of D-channel */
2822                                 time(&pri->lastreset);
2823
2824                                 /* Restart in 5 seconds */
2825                                 if (pri->resetinterval > -1) {
2826                                         pri->lastreset -= pri->resetinterval;
2827                                         pri->lastreset += 5;
2828                                 }
2829                                 pri->resetting = 0;
2830                                 /* Take the channels from inalarm condition */
2831                                 for (i = 0; i < pri->numchans; i++) {
2832                                         if (pri->pvts[i]) {
2833                                                 pri->pvts[i]->inalarm = 0;
2834                                         }
2835                                 }
2836                                 sig_pri_span_devstate_changed(pri);
2837                                 break;
2838                         case PRI_EVENT_DCHAN_DOWN:
2839                                 pri_find_dchan(pri);
2840                                 if (!pri_is_up(pri)) {
2841                                         pri->resetting = 0;
2842                                         if (pri->sig == SIG_BRI_PTMP) {
2843                                                 /* For PTMP connections with non persistent layer 2 we want
2844                                                  * to *not* declare inalarm unless there actually is an alarm */
2845                                                 break;
2846                                         }
2847                                         /* Hangup active channels and put them in alarm mode */
2848                                         for (i = 0; i < pri->numchans; i++) {
2849                                                 struct sig_pri_chan *p = pri->pvts[i];
2850                                                 if (p) {
2851                                                         if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
2852                                                                 /* T309 is not enabled : hangup calls when alarm occurs */
2853                                                                 if (p->call) {
2854                                                                         if (p->pri && p->pri->pri) {
2855                                                                                 pri_hangup(p->pri->pri, p->call, -1);
2856                                                                                 pri_destroycall(p->pri->pri, p->call);
2857                                                                                 p->call = NULL;
2858                                                                         } else
2859                                                                                 ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
2860                                                                 }
2861                                                                 if (p->owner)
2862                                                                         ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
2863                                                         }
2864                                                         p->inalarm = 1;
2865                                                 }
2866                                         }
2867                                         sig_pri_span_devstate_changed(pri);
2868                                 }
2869                                 break;
2870                         case PRI_EVENT_RESTART:
2871                                 if (e->restart.channel > -1) {
2872                                         chanpos = pri_find_principle(pri, e->restart.channel, NULL);
2873                                         if (chanpos < 0)
2874                                                 ast_log(LOG_WARNING, "Restart requested on odd/unavailable channel number %d/%d on span %d\n",
2875                                                         PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
2876                                         else {
2877                                                 int skipit = 0;
2878 #if defined(HAVE_PRI_SERVICE_MESSAGES)
2879                                                 unsigned why;
2880
2881                                                 why = pri->pvts[chanpos]->service_status;
2882                                                 if (why) {
2883                                                         ast_log(LOG_NOTICE,
2884                                                                 "span '%d' channel '%d' out-of-service (reason: %s), ignoring RESTART\n",
2885                                                                 pri->span, PRI_CHANNEL(e->restart.channel),
2886                                                                 (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
2887                                                         skipit = 1;
2888                                                 }
2889 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
2890                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2891                                                 if (!skipit) {
2892                                                         ast_verb(3, "B-channel %d/%d restarted on span %d\n",
2893                                                                 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
2894                                                         if (pri->pvts[chanpos]->call) {
2895                                                                 pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
2896                                                                 pri->pvts[chanpos]->call = NULL;
2897                                                         }
2898                                                 }
2899                                                 /* Force soft hangup if appropriate */
2900                                                 if (pri->pvts[chanpos]->owner)
2901                                                         ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
2902                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2903                                         }
2904                                 } else {
2905                                         ast_verb(3, "Restart requested on entire span %d\n", pri->span);
2906                                         for (x = 0; x < pri->numchans; x++)
2907                                                 if (pri->pvts[x]) {
2908                                                         sig_pri_lock_private(pri->pvts[x]);
2909                                                         if (pri->pvts[x]->call) {
2910                                                                 pri_destroycall(pri->pri, pri->pvts[x]->call);
2911                                                                 pri->pvts[x]->call = NULL;
2912                                                         }
2913                                                         if (pri->pvts[x]->owner)
2914                                                                 ast_softhangup_nolock(pri->pvts[x]->owner, AST_SOFTHANGUP_DEV);
2915                                                         sig_pri_unlock_private(pri->pvts[x]);
2916                                                 }
2917                                 }
2918                                 break;
2919                         case PRI_EVENT_KEYPAD_DIGIT:
2920                                 if (sig_pri_is_cis_call(e->digit.channel)) {
2921                                         sig_pri_handle_cis_subcmds(pri, e->e, e->digit.subcmds,
2922                                                 e->digit.call);
2923                                         break;
2924                                 }
2925                                 chanpos = pri_find_principle(pri, e->digit.channel, e->digit.call);
2926                                 if (chanpos < 0) {
2927                                         ast_log(LOG_WARNING, "KEYPAD_DIGITs received on unconfigured channel %d/%d span %d\n",
2928                                                 PRI_SPAN(e->digit.channel), PRI_CHANNEL(e->digit.channel), pri->span);
2929                                 } else {
2930                                         chanpos = pri_fixup_principle(pri, chanpos, e->digit.call);
2931                                         if (chanpos > -1) {
2932                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2933                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->digit.channel,
2934                                                         e->digit.subcmds, e->digit.call);
2935                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
2936                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
2937                                                         && pri->pvts[chanpos]->call == e->digit.call
2938                                                         && pri->pvts[chanpos]->owner) {
2939                                                         /* how to do that */
2940                                                         int digitlen = strlen(e->digit.digits);
2941                                                         int i;
2942
2943                                                         for (i = 0; i < digitlen; i++) {
2944                                                                 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->digit.digits[i], };
2945
2946                                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
2947                                                         }
2948                                                 }
2949                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2950                                         }
2951                                 }
2952                                 break;
2953
2954                         case PRI_EVENT_INFO_RECEIVED:
2955                                 if (sig_pri_is_cis_call(e->ring.channel)) {
2956                                         sig_pri_handle_cis_subcmds(pri, e->e, e->ring.subcmds,
2957                                                 e->ring.call);
2958                                         break;
2959                                 }
2960                                 chanpos = pri_find_principle(pri, e->ring.channel, e->ring.call);
2961                                 if (chanpos < 0) {
2962                                         ast_log(LOG_WARNING, "INFO received on unconfigured channel %d/%d span %d\n",
2963                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
2964                                 } else {
2965                                         chanpos = pri_fixup_principle(pri, chanpos, e->ring.call);
2966                                         if (chanpos > -1) {
2967                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2968                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
2969                                                         e->ring.subcmds, e->ring.call);
2970                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
2971                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
2972                                                         && pri->pvts[chanpos]->call == e->ring.call
2973                                                         && pri->pvts[chanpos]->owner) {
2974                                                         /* how to do that */
2975                                                         int digitlen = strlen(e->ring.callednum);
2976                                                         int i;
2977
2978                                                         for (i = 0; i < digitlen; i++) {
2979                                                                 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->ring.callednum[i], };
2980
2981                                                                 pri_queue_frame(pri->pvts[chanpos], &f, pri);
2982                                                         }
2983                                                 }
2984                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2985                                         }
2986                                 }
2987                                 break;
2988 #if defined(HAVE_PRI_SERVICE_MESSAGES)
2989                         case PRI_EVENT_SERVICE:
2990                                 chanpos = pri_find_principle(pri, e->service.channel, NULL);
2991                                 if (chanpos < 0) {
2992                                         ast_log(LOG_WARNING, "Received service change status %d on unconfigured channel %d/%d span %d\n",
2993                                                 e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
2994                                 } else {
2995                                         char db_chan_name[20];
2996                                         char db_answer[5];
2997                                         int ch;
2998                                         unsigned *why;
2999
3000                                         ch = pri->pvts[chanpos]->channel;
3001                                         snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->span, ch);
3002                                         why = &pri->pvts[chanpos]->service_status;
3003                                         switch (e->service.changestatus) {
3004                                         case 0: /* in-service */
3005                                                 /* Far end wants to be in service now. */
3006                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
3007                                                 *why &= ~SRVST_FAREND;
3008                                                 if (*why) {
3009                                                         snprintf(db_answer, sizeof(db_answer), "%s:%u",
3010                                                                 SRVST_TYPE_OOS, *why);
3011                                                         ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
3012                                                 } else {
3013                                                         sig_pri_span_devstate_changed(pri);
3014                                                 }
3015                                                 break;
3016                                         case 2: /* out-of-service */
3017                                                 /* Far end wants to be out-of-service now. */
3018                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
3019                                                 *why |= SRVST_FAREND;
3020                                                 snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS,
3021                                                         *why);