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