d5a92c332c81f4561e4705c3aa2ee7045f925d29
[asterisk/asterisk.git] / channels / sig_ss7.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2010 Digium, Inc.
5  *
6  * Richard Mudgett <rmudgett@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 /*!
20  * \file
21  * \brief SS7 signaling module.
22  *
23  * \author Matthew Fredrickson <creslin@digium.com>
24  * \author Richard Mudgett <rmudgett@digium.com>
25  *
26  * See Also:
27  * \arg \ref AstCREDITS
28  */
29
30 /*** MODULEINFO
31         <support_level>core</support_level>
32  ***/
33
34 #include "asterisk.h"
35
36 #if defined(HAVE_SS7)
37
38 #include <signal.h>
39
40 #include "asterisk/pbx.h"
41 #include "asterisk/causes.h"
42 #include "asterisk/musiconhold.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/transcap.h"
45
46 #include "sig_ss7.h"
47 #if defined(LIBSS7_ABI_COMPATIBILITY)
48 #error "Your installed libss7 is not compatible"
49 #endif
50
51 /* ------------------------------------------------------------------- */
52
53 static const char *sig_ss7_call_level2str(enum sig_ss7_call_level level)
54 {
55         switch (level) {
56         case SIG_SS7_CALL_LEVEL_IDLE:
57                 return "Idle";
58         case SIG_SS7_CALL_LEVEL_ALLOCATED:
59                 return "Allocated";
60         case SIG_SS7_CALL_LEVEL_CONTINUITY:
61                 return "Continuity";
62         case SIG_SS7_CALL_LEVEL_SETUP:
63                 return "Setup";
64         case SIG_SS7_CALL_LEVEL_PROCEEDING:
65                 return "Proceeding";
66         case SIG_SS7_CALL_LEVEL_ALERTING:
67                 return "Alerting";
68         case SIG_SS7_CALL_LEVEL_CONNECT:
69                 return "Connect";
70         case SIG_SS7_CALL_LEVEL_GLARE:
71                 return "Glare";
72         }
73         return "Unknown";
74 }
75
76 static void sig_ss7_unlock_private(struct sig_ss7_chan *p)
77 {
78         if (sig_ss7_callbacks.unlock_private) {
79                 sig_ss7_callbacks.unlock_private(p->chan_pvt);
80         }
81 }
82
83 static void sig_ss7_lock_private(struct sig_ss7_chan *p)
84 {
85         if (sig_ss7_callbacks.lock_private) {
86                 sig_ss7_callbacks.lock_private(p->chan_pvt);
87         }
88 }
89
90 static void sig_ss7_deadlock_avoidance_private(struct sig_ss7_chan *p)
91 {
92         if (sig_ss7_callbacks.deadlock_avoidance_private) {
93                 sig_ss7_callbacks.deadlock_avoidance_private(p->chan_pvt);
94         } else {
95                 /* Fallback to the old way if callback not present. */
96                 sig_ss7_unlock_private(p);
97                 sched_yield();
98                 sig_ss7_lock_private(p);
99         }
100 }
101
102 void sig_ss7_set_alarm(struct sig_ss7_chan *p, int in_alarm)
103 {
104         p->inalarm = in_alarm;
105         if (sig_ss7_callbacks.set_alarm) {
106                 sig_ss7_callbacks.set_alarm(p->chan_pvt, in_alarm);
107         }
108 }
109
110 static void sig_ss7_set_dialing(struct sig_ss7_chan *p, int is_dialing)
111 {
112         if (sig_ss7_callbacks.set_dialing) {
113                 sig_ss7_callbacks.set_dialing(p->chan_pvt, is_dialing);
114         }
115 }
116
117 static void sig_ss7_set_digital(struct sig_ss7_chan *p, int is_digital)
118 {
119         if (sig_ss7_callbacks.set_digital) {
120                 sig_ss7_callbacks.set_digital(p->chan_pvt, is_digital);
121         }
122 }
123
124 static void sig_ss7_set_outgoing(struct sig_ss7_chan *p, int is_outgoing)
125 {
126         p->outgoing = is_outgoing;
127         if (sig_ss7_callbacks.set_outgoing) {
128                 sig_ss7_callbacks.set_outgoing(p->chan_pvt, is_outgoing);
129         }
130 }
131
132 static void sig_ss7_set_inservice(struct sig_ss7_chan *p, int is_inservice)
133 {
134         if (sig_ss7_callbacks.set_inservice) {
135                 sig_ss7_callbacks.set_inservice(p->chan_pvt, is_inservice);
136         }
137 }
138
139 static void sig_ss7_set_locallyblocked(struct sig_ss7_chan *p, int is_blocked)
140 {
141         p->locallyblocked = is_blocked;
142         if (sig_ss7_callbacks.set_locallyblocked) {
143                 sig_ss7_callbacks.set_locallyblocked(p->chan_pvt, is_blocked);
144         }
145 }
146
147 static void sig_ss7_set_remotelyblocked(struct sig_ss7_chan *p, int is_blocked)
148 {
149         p->remotelyblocked = is_blocked;
150         if (sig_ss7_callbacks.set_remotelyblocked) {
151                 sig_ss7_callbacks.set_remotelyblocked(p->chan_pvt, is_blocked);
152         }
153 }
154
155 /*!
156  * \internal
157  * \brief Open the SS7 channel media path.
158  * \since 1.8.12
159  *
160  * \param p Channel private control structure.
161  *
162  * \return Nothing
163  */
164 static void sig_ss7_open_media(struct sig_ss7_chan *p)
165 {
166         if (sig_ss7_callbacks.open_media) {
167                 sig_ss7_callbacks.open_media(p->chan_pvt);
168         }
169 }
170
171 /*!
172  * \internal
173  * \brief Set the caller id information in the parent module.
174  * \since 1.8
175  *
176  * \param p sig_ss7 channel structure.
177  *
178  * \return Nothing
179  */
180 static void sig_ss7_set_caller_id(struct sig_ss7_chan *p)
181 {
182         struct ast_party_caller caller;
183
184         if (sig_ss7_callbacks.set_callerid) {
185                 ast_party_caller_init(&caller);
186
187                 caller.id.name.str = p->cid_name;
188                 caller.id.name.presentation = p->callingpres;
189                 caller.id.name.valid = 1;
190
191                 caller.id.number.str = p->cid_num;
192                 caller.id.number.plan = p->cid_ton;
193                 caller.id.number.presentation = p->callingpres;
194                 caller.id.number.valid = 1;
195
196                 if (!ast_strlen_zero(p->cid_subaddr)) {
197                         caller.id.subaddress.valid = 1;
198                         //caller.id.subaddress.type = 0;/* nsap */
199                         //caller.id.subaddress.odd_even_indicator = 0;
200                         caller.id.subaddress.str = p->cid_subaddr;
201                 }
202
203                 caller.ani.number.str = p->cid_ani;
204                 //caller.ani.number.plan = p->xxx;
205                 //caller.ani.number.presentation = p->xxx;
206                 caller.ani.number.valid = 1;
207
208                 caller.ani2 = p->cid_ani2;
209                 sig_ss7_callbacks.set_callerid(p->chan_pvt, &caller);
210         }
211 }
212
213 /*!
214  * \internal
215  * \brief Set the Dialed Number Identifier.
216  * \since 1.8
217  *
218  * \param p sig_ss7 channel structure.
219  * \param dnid Dialed Number Identifier string.
220  *
221  * \return Nothing
222  */
223 static void sig_ss7_set_dnid(struct sig_ss7_chan *p, const char *dnid)
224 {
225         if (sig_ss7_callbacks.set_dnid) {
226                 sig_ss7_callbacks.set_dnid(p->chan_pvt, dnid);
227         }
228 }
229
230 static int sig_ss7_play_tone(struct sig_ss7_chan *p, enum sig_ss7_tone tone)
231 {
232         int res;
233
234         if (sig_ss7_callbacks.play_tone) {
235                 res = sig_ss7_callbacks.play_tone(p->chan_pvt, tone);
236         } else {
237                 res = -1;
238         }
239         return res;
240 }
241
242 static int sig_ss7_set_echocanceller(struct sig_ss7_chan *p, int enable)
243 {
244         if (sig_ss7_callbacks.set_echocanceller) {
245                 return sig_ss7_callbacks.set_echocanceller(p->chan_pvt, enable);
246         }
247         return -1;
248 }
249
250 static void sig_ss7_loopback(struct sig_ss7_chan *p, int enable)
251 {
252         if (p->loopedback != enable) {
253                 p->loopedback = enable;
254                 if (sig_ss7_callbacks.set_loopback) {
255                         sig_ss7_callbacks.set_loopback(p->chan_pvt, enable);
256                 }
257         }
258 }
259
260 static struct ast_channel *sig_ss7_new_ast_channel(struct sig_ss7_chan *p, int state, int ulaw, int transfercapability, char *exten, const struct ast_channel *requestor)
261 {
262         struct ast_channel *ast;
263
264         if (sig_ss7_callbacks.new_ast_channel) {
265                 ast = sig_ss7_callbacks.new_ast_channel(p->chan_pvt, state, ulaw, exten, requestor);
266         } else {
267                 return NULL;
268         }
269         if (!ast) {
270                 return NULL;
271         }
272
273         if (!p->owner) {
274                 p->owner = ast;
275         }
276         p->alreadyhungup = 0;
277         ast_channel_transfercapability_set(ast, transfercapability);
278         pbx_builtin_setvar_helper(ast, "TRANSFERCAPABILITY",
279                 ast_transfercapability2str(transfercapability));
280         if (transfercapability & AST_TRANS_CAP_DIGITAL) {
281                 sig_ss7_set_digital(p, 1);
282         }
283
284         return ast;
285 }
286
287 static void sig_ss7_handle_link_exception(struct sig_ss7_linkset *linkset, int which)
288 {
289         if (sig_ss7_callbacks.handle_link_exception) {
290                 sig_ss7_callbacks.handle_link_exception(linkset, which);
291         }
292 }
293
294 /*!
295  * \internal
296  * \brief Determine if a private channel structure is available.
297  *
298  * \param pvt Channel to determine if available.
299  *
300  * \return TRUE if the channel is available.
301  */
302 static int sig_ss7_is_chan_available(struct sig_ss7_chan *pvt)
303 {
304         if (!pvt->inalarm && !pvt->owner && !pvt->ss7call
305                 && pvt->call_level == SIG_SS7_CALL_LEVEL_IDLE
306                 && !pvt->locallyblocked && !pvt->remotelyblocked) {
307                 return 1;
308         }
309         return 0;
310 }
311
312 /*!
313  * \internal
314  * \brief Obtain the sig_ss7 owner channel lock if the owner exists.
315  * \since 1.8
316  *
317  * \param ss7 SS7 linkset control structure.
318  * \param chanpos Channel position in the span.
319  *
320  * \note Assumes the ss7->lock is already obtained.
321  * \note Assumes the sig_ss7_lock_private(ss7->pvts[chanpos]) is already obtained.
322  *
323  * \return Nothing
324  */
325 static void sig_ss7_lock_owner(struct sig_ss7_linkset *ss7, int chanpos)
326 {
327         for (;;) {
328                 if (!ss7->pvts[chanpos]->owner) {
329                         /* There is no owner lock to get. */
330                         break;
331                 }
332                 if (!ast_channel_trylock(ss7->pvts[chanpos]->owner)) {
333                         /* We got the lock */
334                         break;
335                 }
336
337                 /* Avoid deadlock */
338                 sig_ss7_unlock_private(ss7->pvts[chanpos]);
339                 DEADLOCK_AVOIDANCE(&ss7->lock);
340                 sig_ss7_lock_private(ss7->pvts[chanpos]);
341         }
342 }
343
344 /*!
345  * \internal
346  * \brief Queue the given frame onto the owner channel.
347  * \since 1.8
348  *
349  * \param ss7 SS7 linkset control structure.
350  * \param chanpos Channel position in the span.
351  * \param frame Frame to queue onto the owner channel.
352  *
353  * \note Assumes the ss7->lock is already obtained.
354  * \note Assumes the sig_ss7_lock_private(ss7->pvts[chanpos]) is already obtained.
355  *
356  * \return Nothing
357  */
358 static void sig_ss7_queue_frame(struct sig_ss7_linkset *ss7, int chanpos, struct ast_frame *frame)
359 {
360         sig_ss7_lock_owner(ss7, chanpos);
361         if (ss7->pvts[chanpos]->owner) {
362                 ast_queue_frame(ss7->pvts[chanpos]->owner, frame);
363                 ast_channel_unlock(ss7->pvts[chanpos]->owner);
364         }
365 }
366
367 /*!
368  * \internal
369  * \brief Queue a control frame of the specified subclass onto the owner channel.
370  * \since 1.8
371  *
372  * \param ss7 SS7 linkset control structure.
373  * \param chanpos Channel position in the span.
374  * \param subclass Control frame subclass to queue onto the owner channel.
375  *
376  * \note Assumes the ss7->lock is already obtained.
377  * \note Assumes the sig_ss7_lock_private(ss7->pvts[chanpos]) is already obtained.
378  *
379  * \return Nothing
380  */
381 static void sig_ss7_queue_control(struct sig_ss7_linkset *ss7, int chanpos, int subclass)
382 {
383         struct ast_frame f = {AST_FRAME_CONTROL, };
384         struct sig_ss7_chan *p = ss7->pvts[chanpos];
385
386         if (sig_ss7_callbacks.queue_control) {
387                 sig_ss7_callbacks.queue_control(p->chan_pvt, subclass);
388         }
389
390         f.subclass.integer = subclass;
391         sig_ss7_queue_frame(ss7, chanpos, &f);
392 }
393
394 /*!
395  * \internal
396  * \brief Queue a PVT_CAUSE_CODE frame onto the owner channel.
397  * \since 11
398  *
399  * \param owner Owner channel of the pvt.
400  * \param cause String describing the cause to be placed into the frame.
401  *
402  * \note Assumes the linkset->lock is already obtained.
403  * \note Assumes the sig_ss7_lock_private(linkset->pvts[chanpos]) is already obtained.
404  * \note Assumes linkset->pvts[chanpos]->owner is non-NULL and its lock is already obtained.
405  *
406  * \return Nothing
407  */
408 static void ss7_queue_pvt_cause_data(struct ast_channel *owner, const char *cause, int ast_cause)
409 {
410         struct ast_control_pvt_cause_code *cause_code;
411         int datalen = sizeof(*cause_code) + strlen(cause);
412
413         cause_code = ast_alloca(datalen);
414         cause_code->ast_cause = ast_cause;
415         ast_copy_string(cause_code->chan_name, ast_channel_name(owner), AST_CHANNEL_NAME);
416         ast_copy_string(cause_code->code, cause, datalen + 1 - sizeof(*cause_code));
417         ast_queue_control_data(owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, datalen);
418         ast_channel_hangupcause_hash_set(owner, cause_code, datalen);
419 }
420
421
422 /*!
423  * \internal
424  * \brief Find the channel position by CIC/DPC.
425  *
426  * \param linkset SS7 linkset control structure.
427  * \param cic Circuit Identification Code
428  * \param dpc Destination Point Code
429  *
430  * \retval chanpos on success.
431  * \retval -1 on error.
432  */
433 static int ss7_find_cic(struct sig_ss7_linkset *linkset, int cic, unsigned int dpc)
434 {
435         int i;
436         int winner = -1;
437         for (i = 0; i < linkset->numchans; i++) {
438                 if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && linkset->pvts[i]->cic == cic)) {
439                         winner = i;
440                         break;
441                 }
442         }
443         return winner;
444 }
445
446 /*!
447  * \internal
448  * \brief Find the channel position by CIC/DPC and gripe if not found.
449  *
450  * \param linkset SS7 linkset control structure.
451  * \param cic Circuit Identification Code
452  * \param dpc Destination Point Code
453  * \param msg_name Message type name that failed.
454  *
455  * \retval chanpos on success.
456  * \retval -1 on error.
457  */
458 static int ss7_find_cic_gripe(struct sig_ss7_linkset *linkset, int cic, unsigned int dpc, const char *msg_name)
459 {
460         int chanpos;
461
462         chanpos = ss7_find_cic(linkset, cic, dpc);
463         if (chanpos < 0) {
464                 ast_log(LOG_WARNING, "Linkset %d: SS7 %s requested unconfigured CIC/DPC %d/%d.\n",
465                         linkset->span, msg_name, cic, dpc);
466                 return -1;
467         }
468         return chanpos;
469 }
470
471 static void ss7_handle_cqm(struct sig_ss7_linkset *linkset, int startcic, int endcic, unsigned int dpc)
472 {
473         unsigned char status[32];
474         struct sig_ss7_chan *p = NULL;
475         int i, offset;
476
477         for (i = 0; i < linkset->numchans; i++) {
478                 if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && ((linkset->pvts[i]->cic >= startcic) && (linkset->pvts[i]->cic <= endcic)))) {
479                         p = linkset->pvts[i];
480                         offset = p->cic - startcic;
481                         status[offset] = 0;
482                         if (p->locallyblocked)
483                                 status[offset] |= (1 << 0) | (1 << 4);
484                         if (p->remotelyblocked)
485                                 status[offset] |= (1 << 1) | (1 << 5);
486                         if (p->ss7call) {
487                                 if (p->outgoing)
488                                         status[offset] |= (1 << 3);
489                                 else
490                                         status[offset] |= (1 << 2);
491                         } else
492                                 status[offset] |= 0x3 << 2;
493                 }
494         }
495
496         if (p)
497                 isup_cqr(linkset->ss7, startcic, endcic, dpc, status);
498         else
499                 ast_log(LOG_WARNING, "Could not find any equipped circuits within CQM CICs\n");
500
501 }
502
503 static inline void ss7_hangup_cics(struct sig_ss7_linkset *linkset, int startcic, int endcic, unsigned int dpc)
504 {
505         int i;
506
507         for (i = 0; i < linkset->numchans; i++) {
508                 if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && ((linkset->pvts[i]->cic >= startcic) && (linkset->pvts[i]->cic <= endcic)))) {
509                         sig_ss7_lock_private(linkset->pvts[i]);
510                         sig_ss7_lock_owner(linkset, i);
511                         if (linkset->pvts[i]->owner) {
512                                 ast_softhangup_nolock(linkset->pvts[i]->owner, AST_SOFTHANGUP_DEV);
513                                 ast_channel_unlock(linkset->pvts[i]->owner);
514                         }
515                         sig_ss7_unlock_private(linkset->pvts[i]);
516                 }
517         }
518 }
519
520 static inline void ss7_block_cics(struct sig_ss7_linkset *linkset, int startcic, int endcic, unsigned int dpc, unsigned char state[], int block)
521 {
522         int i;
523
524         /* XXX the use of state here seems questionable about matching up with the linkset channels */
525         for (i = 0; i < linkset->numchans; i++) {
526                 if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && ((linkset->pvts[i]->cic >= startcic) && (linkset->pvts[i]->cic <= endcic)))) {
527                         if (state) {
528                                 if (state[i])
529                                         sig_ss7_set_remotelyblocked(linkset->pvts[i], block);
530                         } else
531                                 sig_ss7_set_remotelyblocked(linkset->pvts[i], block);
532                 }
533         }
534 }
535
536 static void ss7_inservice(struct sig_ss7_linkset *linkset, int startcic, int endcic, unsigned int dpc)
537 {
538         int i;
539
540         for (i = 0; i < linkset->numchans; i++) {
541                 if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && ((linkset->pvts[i]->cic >= startcic) && (linkset->pvts[i]->cic <= endcic))))
542                         sig_ss7_set_inservice(linkset->pvts[i], 1);
543         }
544 }
545
546 static void ss7_reset_linkset(struct sig_ss7_linkset *linkset)
547 {
548         int i, startcic = -1, endcic, dpc;
549
550         if (linkset->numchans <= 0)
551                 return;
552
553         startcic = linkset->pvts[0]->cic;
554         /* DB: CIC's DPC fix */
555         dpc = linkset->pvts[0]->dpc;
556
557         for (i = 0; i < linkset->numchans; i++) {
558                 if (linkset->pvts[i+1] && linkset->pvts[i+1]->dpc == dpc && ((linkset->pvts[i+1]->cic - linkset->pvts[i]->cic) == 1) && (linkset->pvts[i]->cic - startcic < 31)) {
559                         continue;
560                 } else {
561                         endcic = linkset->pvts[i]->cic;
562                         ast_verbose("Resetting CICs %d to %d\n", startcic, endcic);
563                         isup_grs(linkset->ss7, startcic, endcic, dpc);
564
565                         /* DB: CIC's DPC fix */
566                         if (linkset->pvts[i+1]) {
567                                 startcic = linkset->pvts[i+1]->cic;
568                                 dpc = linkset->pvts[i+1]->dpc;
569                         }
570                 }
571         }
572 }
573
574 /* This function is assumed to be called with the private channel lock and linkset lock held */
575 static void ss7_start_call(struct sig_ss7_chan *p, struct sig_ss7_linkset *linkset)
576 {
577         struct ss7 *ss7 = linkset->ss7;
578         int law;
579         struct ast_channel *c;
580         char tmp[256];
581         struct ast_callid *callid = NULL;
582         int callid_created = ast_callid_threadstorage_auto(&callid);
583
584         if (!(linkset->flags & LINKSET_FLAG_EXPLICITACM)) {
585                 p->call_level = SIG_SS7_CALL_LEVEL_PROCEEDING;
586                 isup_acm(ss7, p->ss7call);
587         } else {
588                 p->call_level = SIG_SS7_CALL_LEVEL_SETUP;
589         }
590
591         /* Companding law is determined by SS7 signaling type. */
592         if (linkset->type == SS7_ITU) {
593                 law = SIG_SS7_ALAW;
594         } else {
595                 law = SIG_SS7_ULAW;
596         }
597
598         /*
599          * Release the SS7 lock while we create the channel so other
600          * threads can send messages.  We must also release the private
601          * lock to prevent deadlock while creating the channel.
602          */
603         ast_mutex_unlock(&linkset->lock);
604         sig_ss7_unlock_private(p);
605         c = sig_ss7_new_ast_channel(p, AST_STATE_RING, law, 0, p->exten, NULL);
606         if (!c) {
607                 ast_log(LOG_WARNING, "Unable to start PBX on CIC %d\n", p->cic);
608                 ast_mutex_lock(&linkset->lock);
609                 sig_ss7_lock_private(p);
610                 isup_rel(linkset->ss7, p->ss7call, AST_CAUSE_SWITCH_CONGESTION);
611                 p->call_level = SIG_SS7_CALL_LEVEL_IDLE;
612                 p->alreadyhungup = 1;
613                 ast_callid_threadstorage_auto_clean(callid, callid_created);
614                 return;
615         }
616
617         /* Hold the channel and private lock while we setup the channel. */
618         ast_channel_lock(c);
619         sig_ss7_lock_private(p);
620
621         sig_ss7_set_echocanceller(p, 1);
622
623         /*
624          * It is reasonably safe to set the following
625          * channel variables while the channel private
626          * structure is locked.  The PBX has not been
627          * started yet and it is unlikely that any other task
628          * will do anything with the channel we have just
629          * created.
630          *
631          * We only reference these variables in the context of the ss7_linkset function
632          * when receiving either and IAM or a COT message.
633          */
634         if (!ast_strlen_zero(p->charge_number)) {
635                 pbx_builtin_setvar_helper(c, "SS7_CHARGE_NUMBER", p->charge_number);
636                 /* Clear this after we set it */
637                 p->charge_number[0] = 0;
638         }
639         if (!ast_strlen_zero(p->gen_add_number)) {
640                 pbx_builtin_setvar_helper(c, "SS7_GENERIC_ADDRESS", p->gen_add_number);
641                 /* Clear this after we set it */
642                 p->gen_add_number[0] = 0;
643         }
644         if (!ast_strlen_zero(p->jip_number)) {
645                 pbx_builtin_setvar_helper(c, "SS7_JIP", p->jip_number);
646                 /* Clear this after we set it */
647                 p->jip_number[0] = 0;
648         }
649         if (!ast_strlen_zero(p->gen_dig_number)) {
650                 pbx_builtin_setvar_helper(c, "SS7_GENERIC_DIGITS", p->gen_dig_number);
651                 /* Clear this after we set it */
652                 p->gen_dig_number[0] = 0;
653         }
654         if (!ast_strlen_zero(p->orig_called_num)) {
655                 pbx_builtin_setvar_helper(c, "SS7_ORIG_CALLED_NUM", p->orig_called_num);
656                 /* Clear this after we set it */
657                 p->orig_called_num[0] = 0;
658         }
659
660         snprintf(tmp, sizeof(tmp), "%d", p->gen_dig_type);
661         pbx_builtin_setvar_helper(c, "SS7_GENERIC_DIGTYPE", tmp);
662         /* Clear this after we set it */
663         p->gen_dig_type = 0;
664
665         snprintf(tmp, sizeof(tmp), "%d", p->gen_dig_scheme);
666         pbx_builtin_setvar_helper(c, "SS7_GENERIC_DIGSCHEME", tmp);
667         /* Clear this after we set it */
668         p->gen_dig_scheme = 0;
669
670         if (!ast_strlen_zero(p->lspi_ident)) {
671                 pbx_builtin_setvar_helper(c, "SS7_LSPI_IDENT", p->lspi_ident);
672                 /* Clear this after we set it */
673                 p->lspi_ident[0] = 0;
674         }
675
676         snprintf(tmp, sizeof(tmp), "%d", p->call_ref_ident);
677         pbx_builtin_setvar_helper(c, "SS7_CALLREF_IDENT", tmp);
678         /* Clear this after we set it */
679         p->call_ref_ident = 0;
680
681         snprintf(tmp, sizeof(tmp), "%d", p->call_ref_pc);
682         pbx_builtin_setvar_helper(c, "SS7_CALLREF_PC", tmp);
683         /* Clear this after we set it */
684         p->call_ref_pc = 0;
685
686         snprintf(tmp, sizeof(tmp), "%d", p->calling_party_cat);
687         pbx_builtin_setvar_helper(c, "SS7_CALLING_PARTY_CATEGORY", tmp);
688         /* Clear this after we set it */
689         p->calling_party_cat = 0;
690
691         if (!ast_strlen_zero(p->redirecting_num)) {
692                 pbx_builtin_setvar_helper(c, "SS7_REDIRECTING_NUMBER", p->redirecting_num);
693                 /* Clear this after we set it */
694                 p->redirecting_num[0] = 0;
695         }
696         if (!ast_strlen_zero(p->generic_name)) {
697                 pbx_builtin_setvar_helper(c, "SS7_GENERIC_NAME", p->generic_name);
698                 /* Clear this after we set it */
699                 p->generic_name[0] = 0;
700         }
701
702         sig_ss7_unlock_private(p);
703         ast_channel_unlock(c);
704
705         if (ast_pbx_start(c)) {
706                 ast_log(LOG_WARNING, "Unable to start PBX on %s (CIC %d)\n", ast_channel_name(c), p->cic);
707                 ast_hangup(c);
708         } else {
709                 ast_verb(3, "Accepting call to '%s' on CIC %d\n", p->exten, p->cic);
710         }
711
712         /* Must return with linkset and private lock. */
713         ast_mutex_lock(&linkset->lock);
714         sig_ss7_lock_private(p);
715         ast_callid_threadstorage_auto_clean(callid, callid_created);
716 }
717
718 static void ss7_apply_plan_to_number(char *buf, size_t size, const struct sig_ss7_linkset *ss7, const char *number, const unsigned nai)
719 {
720         if (ast_strlen_zero(number)) { /* make sure a number exists so prefix isn't placed on an empty string */
721                 if (size) {
722                         *buf = '\0';
723                 }
724                 return;
725         }
726         switch (nai) {
727         case SS7_NAI_INTERNATIONAL:
728                 snprintf(buf, size, "%s%s", ss7->internationalprefix, number);
729                 break;
730         case SS7_NAI_NATIONAL:
731                 snprintf(buf, size, "%s%s", ss7->nationalprefix, number);
732                 break;
733         case SS7_NAI_SUBSCRIBER:
734                 snprintf(buf, size, "%s%s", ss7->subscriberprefix, number);
735                 break;
736         case SS7_NAI_UNKNOWN:
737                 snprintf(buf, size, "%s%s", ss7->unknownprefix, number);
738                 break;
739         default:
740                 snprintf(buf, size, "%s", number);
741                 break;
742         }
743 }
744
745 static int ss7_pres_scr2cid_pres(char presentation_ind, char screening_ind)
746 {
747         return ((presentation_ind & 0x3) << 5) | (screening_ind & 0x3);
748 }
749
750 /*!
751  * \internal
752  * \brief Set callid threadstorage for the ss7_linkset thread to that of an existing channel
753  *
754  * \param linkset ss7 span control structure.
755  * \param chanpos channel position in the span
756  *
757  * \note Assumes the ss7->lock is already obtained.
758  * \note Assumes the sig_ss7_lock_private(ss7->pvts[chanpos]) is already obtained.
759  *
760  * \return a reference to the callid bound to the channel which has also
761  *         been bound to threadstorage if it exists. If this returns non-NULL,
762  *         the callid must be unreffed and the threadstorage should be unbound
763  *         before the while loop wraps in ss7_linkset.
764  */
765 static struct ast_callid *func_ss7_linkset_callid(struct sig_ss7_linkset *linkset, int chanpos)
766 {
767         struct ast_callid *callid = NULL;
768         sig_ss7_lock_owner(linkset, chanpos);
769         if (linkset->pvts[chanpos]->owner) {
770                 callid = ast_channel_callid(linkset->pvts[chanpos]->owner);
771                 ast_channel_unlock(linkset->pvts[chanpos]->owner);
772                 if (callid) {
773                         ast_callid_threadassoc_add(callid);
774                 }
775         }
776
777         return callid;
778 }
779
780 /* This is a thread per linkset that handles all received events from libss7. */
781 void *ss7_linkset(void *data)
782 {
783         int res, i;
784         struct timeval *next = NULL, tv;
785         struct sig_ss7_linkset *linkset = (struct sig_ss7_linkset *) data;
786         struct ss7 *ss7 = linkset->ss7;
787         ss7_event *e = NULL;
788         struct sig_ss7_chan *p;
789         struct pollfd pollers[SIG_SS7_NUM_DCHANS];
790         int nextms = 0;
791
792         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
793
794         ss7_set_debug(ss7, SIG_SS7_DEBUG_DEFAULT);
795         ast_mutex_lock(&linkset->lock);
796         ss7_start(ss7);
797         ast_mutex_unlock(&linkset->lock);
798
799         for (;;) {
800                 ast_mutex_lock(&linkset->lock);
801                 if ((next = ss7_schedule_next(ss7))) {
802                         tv = ast_tvnow();
803                         tv.tv_sec = next->tv_sec - tv.tv_sec;
804                         tv.tv_usec = next->tv_usec - tv.tv_usec;
805                         if (tv.tv_usec < 0) {
806                                 tv.tv_usec += 1000000;
807                                 tv.tv_sec -= 1;
808                         }
809                         if (tv.tv_sec < 0) {
810                                 tv.tv_sec = 0;
811                                 tv.tv_usec = 0;
812                         }
813                         nextms = tv.tv_sec * 1000;
814                         nextms += tv.tv_usec / 1000;
815                 }
816
817                 for (i = 0; i < linkset->numsigchans; i++) {
818                         pollers[i].fd = linkset->fds[i];
819                         pollers[i].events = ss7_pollflags(ss7, linkset->fds[i]);
820                         pollers[i].revents = 0;
821                 }
822                 ast_mutex_unlock(&linkset->lock);
823
824                 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
825                 pthread_testcancel();
826                 res = poll(pollers, linkset->numsigchans, nextms);
827                 pthread_testcancel();
828                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
829
830                 if ((res < 0) && (errno != EINTR)) {
831                         ast_log(LOG_ERROR, "poll(%s)\n", strerror(errno));
832                 } else if (!res) {
833                         ast_mutex_lock(&linkset->lock);
834                         ss7_schedule_run(ss7);
835                         ast_mutex_unlock(&linkset->lock);
836                         continue;
837                 }
838
839                 ast_mutex_lock(&linkset->lock);
840                 for (i = 0; i < linkset->numsigchans; i++) {
841                         if (pollers[i].revents & POLLPRI) {
842                                 sig_ss7_handle_link_exception(linkset, i);
843                         }
844                         if (pollers[i].revents & POLLIN) {
845                                 res = ss7_read(ss7, pollers[i].fd);
846                         }
847                         if (pollers[i].revents & POLLOUT) {
848                                 res = ss7_write(ss7, pollers[i].fd);
849                                 if (res < 0) {
850                                         ast_debug(1, "Error in write %s\n", strerror(errno));
851                                 }
852                         }
853                 }
854
855                 while ((e = ss7_check_event(ss7))) {
856                         struct ast_callid *callid = NULL;
857                         int chanpos = -1;
858                         char cause_str[30];
859
860                         if (linkset->debug) {
861                                 ast_verbose("Linkset %d: Processing event: %s\n",
862                                         linkset->span, ss7_event2str(e->e));
863                         }
864
865                         switch (e->e) {
866                         case SS7_EVENT_UP:
867                                 if (linkset->state != LINKSET_STATE_UP) {
868                                         ast_verbose("--- SS7 Up ---\n");
869                                         ss7_reset_linkset(linkset);
870                                 }
871                                 linkset->state = LINKSET_STATE_UP;
872                                 break;
873                         case SS7_EVENT_DOWN:
874                                 ast_verbose("--- SS7 Down ---\n");
875                                 linkset->state = LINKSET_STATE_DOWN;
876                                 for (i = 0; i < linkset->numchans; i++) {
877                                         p = linkset->pvts[i];
878                                         if (p) {
879                                                 sig_ss7_set_alarm(p, 1);
880                                         }
881                                 }
882                                 break;
883                         case MTP2_LINK_UP:
884                                 ast_verbose("MTP2 link up (SLC %d)\n", e->gen.data);
885                                 break;
886                         case MTP2_LINK_DOWN:
887                                 ast_log(LOG_WARNING, "MTP2 link down (SLC %d)\n", e->gen.data);
888                                 break;
889                         case ISUP_EVENT_CPG:
890                                 chanpos = ss7_find_cic_gripe(linkset, e->cpg.cic, e->cpg.opc, "CPG");
891                                 if (chanpos < 0) {
892                                         break;
893                                 }
894                                 p = linkset->pvts[chanpos];
895                                 sig_ss7_lock_private(p);
896                                 callid = func_ss7_linkset_callid(linkset, chanpos);
897
898                                 switch (e->cpg.event) {
899                                 case CPG_EVENT_ALERTING:
900                                         if (p->call_level < SIG_SS7_CALL_LEVEL_ALERTING) {
901                                                 p->call_level = SIG_SS7_CALL_LEVEL_ALERTING;
902                                         }
903                                         sig_ss7_lock_owner(linkset, chanpos);
904                                         if (p->owner) {
905                                                 ast_setstate(p->owner, AST_STATE_RINGING);
906                                                 ast_channel_unlock(p->owner);
907                                         }
908                                         sig_ss7_queue_control(linkset, chanpos, AST_CONTROL_RINGING);
909                                         break;
910                                 case CPG_EVENT_PROGRESS:
911                                 case CPG_EVENT_INBANDINFO:
912                                         {
913                                                 ast_debug(1, "Queuing frame PROGRESS on CIC %d\n", p->cic);
914                                                 sig_ss7_queue_control(linkset, chanpos, AST_CONTROL_PROGRESS);
915                                                 p->progress = 1;
916                                                 sig_ss7_set_dialing(p, 0);
917                                                 sig_ss7_open_media(p);
918                                         }
919                                         break;
920                                 default:
921                                         ast_debug(1, "Do not handle CPG with event type 0x%x\n", e->cpg.event);
922                                         break;
923                                 }
924
925                                 sig_ss7_unlock_private(p);
926                                 break;
927                         case ISUP_EVENT_RSC:
928                                 ast_verbose("Resetting CIC %d\n", e->rsc.cic);
929                                 chanpos = ss7_find_cic_gripe(linkset, e->rsc.cic, e->rsc.opc, "RSC");
930                                 if (chanpos < 0) {
931                                         break;
932                                 }
933                                 p = linkset->pvts[chanpos];
934                                 sig_ss7_lock_private(p);
935                                 callid = func_ss7_linkset_callid(linkset, chanpos);
936                                 sig_ss7_set_inservice(p, 1);
937                                 sig_ss7_set_remotelyblocked(p, 0);
938                                 isup_set_call_dpc(e->rsc.call, p->dpc);
939                                 sig_ss7_lock_owner(linkset, chanpos);
940                                 p->ss7call = NULL;
941                                 if (p->owner) {
942                                         ss7_queue_pvt_cause_data(p->owner, "SS7 ISUP_EVENT_RSC", AST_CAUSE_INTERWORKING);
943                                         ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
944                                         ast_channel_unlock(p->owner);
945                                 }
946                                 sig_ss7_unlock_private(p);
947                                 isup_rlc(ss7, e->rsc.call);
948                                 break;
949                         case ISUP_EVENT_GRS:
950                                 ast_debug(1, "Got Reset for CICs %d to %d: Acknowledging\n", e->grs.startcic, e->grs.endcic);
951                                 chanpos = ss7_find_cic_gripe(linkset, e->grs.startcic, e->grs.opc, "GRS");
952                                 if (chanpos < 0) {
953                                         break;
954                                 }
955                                 p = linkset->pvts[chanpos];
956                                 isup_gra(ss7, e->grs.startcic, e->grs.endcic, e->grs.opc);
957                                 ss7_block_cics(linkset, e->grs.startcic, e->grs.endcic, e->grs.opc, NULL, 0);
958                                 ss7_hangup_cics(linkset, e->grs.startcic, e->grs.endcic, e->grs.opc);
959                                 break;
960                         case ISUP_EVENT_CQM:
961                                 ast_debug(1, "Got Circuit group query message from CICs %d to %d\n", e->cqm.startcic, e->cqm.endcic);
962                                 ss7_handle_cqm(linkset, e->cqm.startcic, e->cqm.endcic, e->cqm.opc);
963                                 break;
964                         case ISUP_EVENT_GRA:
965                                 ast_verbose("Got reset acknowledgement from CIC %d to %d.\n", e->gra.startcic, e->gra.endcic);
966                                 ss7_inservice(linkset, e->gra.startcic, e->gra.endcic, e->gra.opc);
967                                 ss7_block_cics(linkset, e->gra.startcic, e->gra.endcic, e->gra.opc, e->gra.status, 1);
968                                 break;
969                         case ISUP_EVENT_IAM:
970                                 ast_debug(1, "Got IAM for CIC %d and called number %s, calling number %s\n", e->iam.cic, e->iam.called_party_num, e->iam.calling_party_num);
971                                 chanpos = ss7_find_cic_gripe(linkset, e->iam.cic, e->iam.opc, "IAM");
972                                 if (chanpos < 0) {
973                                         isup_rel(ss7, e->iam.call, -1);
974                                         break;
975                                 }
976                                 p = linkset->pvts[chanpos];
977                                 sig_ss7_lock_private(p);
978                                 sig_ss7_lock_owner(linkset, chanpos);
979                                 if (p->call_level != SIG_SS7_CALL_LEVEL_IDLE) {
980                                         /*
981                                          * Detected glare/dual-seizure
982                                          *
983                                          * Always abort both calls since we can't implement the dual
984                                          * seizure procedures due to our channel assignment architecture
985                                          * and the fact that we cannot tell libss7 to discard its call
986                                          * structure to ignore the incoming IAM.
987                                          */
988                                         ast_debug(1,
989                                                 "Linkset %d: SS7 IAM glare on CIC/DPC %d/%d.  Dropping both calls.\n",
990                                                 linkset->span, e->iam.cic, e->iam.opc);
991                                         if (p->call_level == SIG_SS7_CALL_LEVEL_ALLOCATED) {
992                                                 /*
993                                                  * We have not sent our IAM yet and we never will at this point.
994                                                  */
995                                                 p->alreadyhungup = 1;
996                                                 isup_rel(ss7, e->iam.call, AST_CAUSE_NORMAL_CIRCUIT_CONGESTION);
997                                         }
998                                         p->call_level = SIG_SS7_CALL_LEVEL_GLARE;
999                                         if (p->owner) {
1000                                                 ss7_queue_pvt_cause_data(p->owner, "SS7 ISUP_EVENT_IAM (glare)", AST_CAUSE_NORMAL_CIRCUIT_CONGESTION);
1001                                                 ast_channel_hangupcause_set(p->owner, AST_CAUSE_NORMAL_CIRCUIT_CONGESTION);
1002                                                 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
1003                                                 ast_channel_unlock(p->owner);
1004                                         }
1005                                         sig_ss7_unlock_private(p);
1006                                         break;
1007                                 }
1008                                 /*
1009                                  * The channel should not have an owner at this point since we
1010                                  * are in the process of creating an owner for it.
1011                                  */
1012                                 ast_assert(!p->owner);
1013
1014                                 if (!sig_ss7_is_chan_available(p)) {
1015                                         /* Circuit is likely blocked or in alarm. */
1016                                         isup_rel(ss7, e->iam.call, AST_CAUSE_NORMAL_CIRCUIT_CONGESTION);
1017                                         sig_ss7_unlock_private(p);
1018                                         break;
1019                                 }
1020
1021                                 /* Mark channel as in use so no outgoing call will steal it. */
1022                                 p->call_level = SIG_SS7_CALL_LEVEL_ALLOCATED;
1023                                 p->ss7call = e->iam.call;
1024
1025                                 isup_set_call_dpc(p->ss7call, p->dpc);
1026
1027                                 if ((p->use_callerid) && (!ast_strlen_zero(e->iam.calling_party_num))) {
1028                                         ss7_apply_plan_to_number(p->cid_num, sizeof(p->cid_num), linkset, e->iam.calling_party_num, e->iam.calling_nai);
1029                                         p->callingpres = ss7_pres_scr2cid_pres(e->iam.presentation_ind, e->iam.screening_ind);
1030                                 } else
1031                                         p->cid_num[0] = 0;
1032
1033                                 /* Set DNID */
1034                                 if (!ast_strlen_zero(e->iam.called_party_num)) {
1035                                         ss7_apply_plan_to_number(p->exten, sizeof(p->exten), linkset,
1036                                                 e->iam.called_party_num, e->iam.called_nai);
1037                                 } else {
1038                                         p->exten[0] = '\0';
1039                                 }
1040                                 sig_ss7_set_dnid(p, p->exten);
1041
1042                                 if (p->immediate) {
1043                                         p->exten[0] = 's';
1044                                         p->exten[1] = '\0';
1045                                 } else if (!ast_strlen_zero(e->iam.called_party_num)) {
1046                                         char *st;
1047                                         ss7_apply_plan_to_number(p->exten, sizeof(p->exten), linkset, e->iam.called_party_num, e->iam.called_nai);
1048                                         st = strchr(p->exten, '#');
1049                                         if (st) {
1050                                                 *st = '\0';
1051                                         }
1052                                 } else {
1053                                         p->exten[0] = '\0';
1054                                 }
1055
1056                                 p->cid_ani[0] = '\0';
1057                                 if ((p->use_callerid) && (!ast_strlen_zero(e->iam.generic_name)))
1058                                         ast_copy_string(p->cid_name, e->iam.generic_name, sizeof(p->cid_name));
1059                                 else
1060                                         p->cid_name[0] = '\0';
1061
1062                                 p->cid_ani2 = e->iam.oli_ani2;
1063                                 p->cid_ton = 0;
1064                                 ast_copy_string(p->charge_number, e->iam.charge_number, sizeof(p->charge_number));
1065                                 ast_copy_string(p->gen_add_number, e->iam.gen_add_number, sizeof(p->gen_add_number));
1066                                 p->gen_add_type = e->iam.gen_add_type;
1067                                 p->gen_add_nai = e->iam.gen_add_nai;
1068                                 p->gen_add_pres_ind = e->iam.gen_add_pres_ind;
1069                                 p->gen_add_num_plan = e->iam.gen_add_num_plan;
1070                                 ast_copy_string(p->gen_dig_number, e->iam.gen_dig_number, sizeof(p->gen_dig_number));
1071                                 p->gen_dig_type = e->iam.gen_dig_type;
1072                                 p->gen_dig_scheme = e->iam.gen_dig_scheme;
1073                                 ast_copy_string(p->jip_number, e->iam.jip_number, sizeof(p->jip_number));
1074                                 ast_copy_string(p->orig_called_num, e->iam.orig_called_num, sizeof(p->orig_called_num));
1075                                 ast_copy_string(p->redirecting_num, e->iam.redirecting_num, sizeof(p->redirecting_num));
1076                                 ast_copy_string(p->generic_name, e->iam.generic_name, sizeof(p->generic_name));
1077                                 p->calling_party_cat = e->iam.calling_party_cat;
1078
1079                                 sig_ss7_set_caller_id(p);
1080
1081                                 if (ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
1082                                         if (e->iam.cot_check_required) {
1083                                                 p->call_level = SIG_SS7_CALL_LEVEL_CONTINUITY;
1084                                                 sig_ss7_loopback(p, 1);
1085                                         } else {
1086                                                 ss7_start_call(p, linkset);
1087                                         }
1088                                 } else {
1089                                         ast_debug(1, "Call on CIC for unconfigured extension %s\n", p->exten);
1090                                         p->alreadyhungup = 1;
1091                                         isup_rel(ss7, e->iam.call, AST_CAUSE_UNALLOCATED);
1092                                 }
1093                                 sig_ss7_unlock_private(p);
1094                                 break;
1095                         case ISUP_EVENT_COT:
1096                                 chanpos = ss7_find_cic_gripe(linkset, e->cot.cic, e->cot.opc, "COT");
1097                                 if (chanpos < 0) {
1098                                         isup_rel(ss7, e->cot.call, -1);
1099                                         break;
1100                                 }
1101                                 p = linkset->pvts[chanpos];
1102
1103                                 sig_ss7_lock_private(p);
1104                                 if (p->loopedback) {
1105                                         sig_ss7_loopback(p, 0);
1106                                         ss7_start_call(p, linkset);
1107                                 }
1108                                 sig_ss7_unlock_private(p);
1109                                 break;
1110                         case ISUP_EVENT_CCR:
1111                                 ast_debug(1, "Got CCR request on CIC %d\n", e->ccr.cic);
1112                                 chanpos = ss7_find_cic_gripe(linkset, e->ccr.cic, e->ccr.opc, "CCR");
1113                                 if (chanpos < 0) {
1114                                         break;
1115                                 }
1116
1117                                 p = linkset->pvts[chanpos];
1118
1119                                 sig_ss7_lock_private(p);
1120                                 sig_ss7_loopback(p, 1);
1121                                 sig_ss7_unlock_private(p);
1122
1123                                 isup_lpa(linkset->ss7, e->ccr.cic, p->dpc);
1124                                 break;
1125                         case ISUP_EVENT_CVT:
1126                                 ast_debug(1, "Got CVT request on CIC %d\n", e->cvt.cic);
1127                                 chanpos = ss7_find_cic_gripe(linkset, e->cvt.cic, e->cvt.opc, "CVT");
1128                                 if (chanpos < 0) {
1129                                         break;
1130                                 }
1131
1132                                 p = linkset->pvts[chanpos];
1133
1134                                 sig_ss7_lock_private(p);
1135                                 sig_ss7_loopback(p, 1);
1136                                 sig_ss7_unlock_private(p);
1137
1138                                 isup_cvr(linkset->ss7, e->cvt.cic, p->dpc);
1139                                 break;
1140                         case ISUP_EVENT_REL:
1141                                 chanpos = ss7_find_cic_gripe(linkset, e->rel.cic, e->rel.opc, "REL");
1142                                 if (chanpos < 0) {
1143                                         /* Continue hanging up the call anyway. */
1144                                         isup_rlc(ss7, e->rel.call);
1145                                         break;
1146                                 }
1147                                 p = linkset->pvts[chanpos];
1148                                 sig_ss7_lock_private(p);
1149                                 callid = func_ss7_linkset_callid(linkset, chanpos);
1150                                 sig_ss7_lock_owner(linkset, chanpos);
1151                                 if (p->owner) {
1152                                         snprintf(cause_str, sizeof(cause_str), "SS7 ISUP_EVENT_REL (%d)", e->rel.cause);
1153                                         ss7_queue_pvt_cause_data(p->owner, cause_str, e->rel.cause);
1154
1155                                         ast_channel_hangupcause_set(p->owner, e->rel.cause);
1156                                         ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
1157                                         ast_channel_unlock(p->owner);
1158                                 }
1159
1160                                 /* End the loopback if we have one */
1161                                 sig_ss7_loopback(p, 0);
1162
1163                                 isup_rlc(ss7, e->rel.call);
1164                                 p->ss7call = NULL;
1165
1166                                 sig_ss7_unlock_private(p);
1167                                 break;
1168                         case ISUP_EVENT_ACM:
1169                                 chanpos = ss7_find_cic_gripe(linkset, e->acm.cic, e->acm.opc, "ACM");
1170                                 if (chanpos < 0) {
1171                                         isup_rel(ss7, e->acm.call, -1);
1172                                         break;
1173                                 }
1174                                 {
1175                                         p = linkset->pvts[chanpos];
1176
1177                                         ast_debug(1, "Queueing frame from SS7_EVENT_ACM on CIC %d\n", p->cic);
1178
1179                                         if (e->acm.call_ref_ident > 0) {
1180                                                 p->rlt = 1; /* Setting it but not using it here*/
1181                                         }
1182
1183                                         sig_ss7_lock_private(p);
1184                                         callid = func_ss7_linkset_callid(linkset, chanpos);
1185                                         sig_ss7_queue_control(linkset, chanpos, AST_CONTROL_PROCEEDING);
1186                                         if (p->call_level < SIG_SS7_CALL_LEVEL_PROCEEDING) {
1187                                                 p->call_level = SIG_SS7_CALL_LEVEL_PROCEEDING;
1188                                         }
1189                                         sig_ss7_set_dialing(p, 0);
1190                                         /* Send alerting if subscriber is free */
1191                                         if (e->acm.called_party_status_ind == 1) {
1192                                                 if (p->call_level < SIG_SS7_CALL_LEVEL_ALERTING) {
1193                                                         p->call_level = SIG_SS7_CALL_LEVEL_ALERTING;
1194                                                 }
1195                                                 sig_ss7_lock_owner(linkset, chanpos);
1196                                                 if (p->owner) {
1197                                                         ast_setstate(p->owner, AST_STATE_RINGING);
1198                                                         ast_channel_unlock(p->owner);
1199                                                 }
1200                                                 sig_ss7_queue_control(linkset, chanpos, AST_CONTROL_RINGING);
1201                                         }
1202                                         sig_ss7_unlock_private(p);
1203                                 }
1204                                 break;
1205                         case ISUP_EVENT_CGB:
1206                                 chanpos = ss7_find_cic_gripe(linkset, e->cgb.startcic, e->cgb.opc, "CGB");
1207                                 if (chanpos < 0) {
1208                                         break;
1209                                 }
1210                                 p = linkset->pvts[chanpos];
1211                                 ss7_block_cics(linkset, e->cgb.startcic, e->cgb.endcic, e->cgb.opc, e->cgb.status, 1);
1212                                 isup_cgba(linkset->ss7, e->cgb.startcic, e->cgb.endcic, e->cgb.opc, e->cgb.status, e->cgb.type);
1213                                 break;
1214                         case ISUP_EVENT_CGU:
1215                                 chanpos = ss7_find_cic_gripe(linkset, e->cgu.startcic, e->cgu.opc, "CGU");
1216                                 if (chanpos < 0) {
1217                                         break;
1218                                 }
1219                                 p = linkset->pvts[chanpos];
1220                                 ss7_block_cics(linkset, e->cgu.startcic, e->cgu.endcic, e->cgu.opc, e->cgu.status, 0);
1221                                 isup_cgua(linkset->ss7, e->cgu.startcic, e->cgu.endcic, e->cgu.opc, e->cgu.status, e->cgu.type);
1222                                 break;
1223                         case ISUP_EVENT_UCIC:
1224                                 chanpos = ss7_find_cic_gripe(linkset, e->ucic.cic, e->ucic.opc, "UCIC");
1225                                 if (chanpos < 0) {
1226                                         break;
1227                                 }
1228                                 p = linkset->pvts[chanpos];
1229                                 ast_debug(1, "Unequiped Circuit Id Code on CIC %d\n", e->ucic.cic);
1230                                 sig_ss7_lock_private(p);
1231                                 sig_ss7_set_remotelyblocked(p, 1);
1232                                 sig_ss7_set_inservice(p, 0);
1233                                 sig_ss7_unlock_private(p);/* doesn't require a SS7 acknowledgement */
1234                                 break;
1235                         case ISUP_EVENT_BLO:
1236                                 chanpos = ss7_find_cic_gripe(linkset, e->blo.cic, e->blo.opc, "BLO");
1237                                 if (chanpos < 0) {
1238                                         break;
1239                                 }
1240                                 p = linkset->pvts[chanpos];
1241                                 ast_debug(1, "Blocking CIC %d\n", e->blo.cic);
1242                                 sig_ss7_lock_private(p);
1243                                 sig_ss7_set_remotelyblocked(p, 1);
1244                                 sig_ss7_unlock_private(p);
1245                                 isup_bla(linkset->ss7, e->blo.cic, p->dpc);
1246                                 break;
1247                         case ISUP_EVENT_BLA:
1248                                 chanpos = ss7_find_cic_gripe(linkset, e->bla.cic, e->bla.opc, "BLA");
1249                                 if (chanpos < 0) {
1250                                         break;
1251                                 }
1252                                 ast_debug(1, "Blocking CIC %d\n", e->bla.cic);
1253                                 p = linkset->pvts[chanpos];
1254                                 sig_ss7_lock_private(p);
1255                                 sig_ss7_set_locallyblocked(p, 1);
1256                                 sig_ss7_unlock_private(p);
1257                                 break;
1258                         case ISUP_EVENT_UBL:
1259                                 chanpos = ss7_find_cic_gripe(linkset, e->ubl.cic, e->ubl.opc, "UBL");
1260                                 if (chanpos < 0) {
1261                                         break;
1262                                 }
1263                                 p = linkset->pvts[chanpos];
1264                                 ast_debug(1, "Unblocking CIC %d\n", e->ubl.cic);
1265                                 sig_ss7_lock_private(p);
1266                                 sig_ss7_set_remotelyblocked(p, 0);
1267                                 sig_ss7_unlock_private(p);
1268                                 isup_uba(linkset->ss7, e->ubl.cic, p->dpc);
1269                                 break;
1270                         case ISUP_EVENT_UBA:
1271                                 chanpos = ss7_find_cic_gripe(linkset, e->uba.cic, e->uba.opc, "UBA");
1272                                 if (chanpos < 0) {
1273                                         break;
1274                                 }
1275                                 p = linkset->pvts[chanpos];
1276                                 ast_debug(1, "Unblocking CIC %d\n", e->uba.cic);
1277                                 sig_ss7_lock_private(p);
1278                                 sig_ss7_set_locallyblocked(p, 0);
1279                                 sig_ss7_unlock_private(p);
1280                                 break;
1281                         case ISUP_EVENT_CON:
1282                         case ISUP_EVENT_ANM:
1283                                 if (e->e == ISUP_EVENT_CON) {
1284                                         chanpos = ss7_find_cic_gripe(linkset, e->con.cic, e->con.opc, "CON");
1285                                         if (chanpos < 0) {
1286                                                 isup_rel(ss7, e->con.call, -1);
1287                                                 break;
1288                                         }
1289                                 } else {
1290                                         chanpos = ss7_find_cic_gripe(linkset, e->anm.cic, e->anm.opc, "ANM");
1291                                         if (chanpos < 0) {
1292                                                 isup_rel(ss7, e->anm.call, -1);
1293                                                 break;
1294                                         }
1295                                 }
1296
1297                                 {
1298                                         p = linkset->pvts[chanpos];
1299                                         sig_ss7_lock_private(p);
1300                                         callid = func_ss7_linkset_callid(linkset, chanpos);
1301                                         if (p->call_level < SIG_SS7_CALL_LEVEL_CONNECT) {
1302                                                 p->call_level = SIG_SS7_CALL_LEVEL_CONNECT;
1303                                         }
1304                                         sig_ss7_queue_control(linkset, chanpos, AST_CONTROL_ANSWER);
1305                                         sig_ss7_set_dialing(p, 0);
1306                                         sig_ss7_open_media(p);
1307                                         sig_ss7_set_echocanceller(p, 1);
1308                                         sig_ss7_unlock_private(p);
1309                                 }
1310                                 break;
1311                         case ISUP_EVENT_RLC:
1312                                 /* XXX Call ptr should be passed up from libss7! */
1313                                 chanpos = ss7_find_cic_gripe(linkset, e->rlc.cic, e->rlc.opc, "RLC");
1314                                 if (chanpos < 0) {
1315                                         break;
1316                                 }
1317                                 {
1318                                         p = linkset->pvts[chanpos];
1319                                         sig_ss7_lock_private(p);
1320                                         callid = func_ss7_linkset_callid(linkset, chanpos);
1321                                         if (p->alreadyhungup) {
1322                                                 if (!p->owner) {
1323                                                         p->call_level = SIG_SS7_CALL_LEVEL_IDLE;
1324                                                 }
1325                                                 p->ss7call = NULL;
1326                                         }
1327                                         sig_ss7_unlock_private(p);
1328                                 }
1329                                 break;
1330                         case ISUP_EVENT_FAA:
1331                                 /*!
1332                                  * \todo The handling of the SS7 FAA message is not good and I
1333                                  * don't know enough to handle it correctly.
1334                                  */
1335                                 chanpos = ss7_find_cic_gripe(linkset, e->faa.cic, e->faa.opc, "FAA");
1336                                 if (chanpos < 0) {
1337                                         isup_rel(linkset->ss7, e->faa.call, -1);
1338                                         break;
1339                                 }
1340                                 {
1341                                         /* XXX FAR and FAA used for something dealing with transfers? */
1342                                         p = linkset->pvts[chanpos];
1343                                         ast_debug(1, "FAA received on CIC %d\n", e->faa.cic);
1344                                         sig_ss7_lock_private(p);
1345                                         callid = func_ss7_linkset_callid(linkset, chanpos);
1346                                         if (p->alreadyhungup){
1347                                                 if (!p->owner) {
1348                                                         p->call_level = SIG_SS7_CALL_LEVEL_IDLE;
1349                                                 }
1350                                                 /* XXX We seem to be leaking the isup call structure here. */
1351                                                 p->ss7call = NULL;
1352                                                 ast_log(LOG_NOTICE, "Received FAA and we haven't sent FAR.  Ignoring.\n");
1353                                         }
1354                                         sig_ss7_unlock_private(p);
1355                                 }
1356                                 break;
1357                         default:
1358                                 ast_debug(1, "Unknown event %s\n", ss7_event2str(e->e));
1359                                 break;
1360                         }
1361
1362                         /* Call ID stuff needs to be cleaned up here */
1363                         if (callid) {
1364                                 callid = ast_callid_unref(callid);
1365                                 ast_callid_threadassoc_remove();
1366                         }
1367                 }
1368                 ast_mutex_unlock(&linkset->lock);
1369         }
1370
1371         return 0;
1372 }
1373
1374 static inline void ss7_rel(struct sig_ss7_linkset *ss7)
1375 {
1376         ast_mutex_unlock(&ss7->lock);
1377 }
1378
1379 static void ss7_grab(struct sig_ss7_chan *pvt, struct sig_ss7_linkset *ss7)
1380 {
1381         /* Grab the lock first */
1382         while (ast_mutex_trylock(&ss7->lock)) {
1383                 /* Avoid deadlock */
1384                 sig_ss7_deadlock_avoidance_private(pvt);
1385         }
1386         /* Then break the poll */
1387         if (ss7->master != AST_PTHREADT_NULL) {
1388                 pthread_kill(ss7->master, SIGURG);
1389         }
1390 }
1391
1392 /*!
1393  * \brief Notify the SS7 layer that the link is in alarm.
1394  * \since 1.8
1395  *
1396  * \param linkset Controlling linkset for the channel.
1397  * \param which Link index of the signaling channel.
1398  *
1399  * \return Nothing
1400  */
1401 void sig_ss7_link_alarm(struct sig_ss7_linkset *linkset, int which)
1402 {
1403         linkset->linkstate[which] |= (LINKSTATE_DOWN | LINKSTATE_INALARM);
1404         linkset->linkstate[which] &= ~LINKSTATE_UP;
1405         ss7_link_alarm(linkset->ss7, linkset->fds[which]);
1406 }
1407
1408 /*!
1409  * \brief Notify the SS7 layer that the link is no longer in alarm.
1410  * \since 1.8
1411  *
1412  * \param linkset Controlling linkset for the channel.
1413  * \param which Link index of the signaling channel.
1414  *
1415  * \return Nothing
1416  */
1417 void sig_ss7_link_noalarm(struct sig_ss7_linkset *linkset, int which)
1418 {
1419         linkset->linkstate[which] &= ~(LINKSTATE_INALARM | LINKSTATE_DOWN);
1420         linkset->linkstate[which] |= LINKSTATE_STARTING;
1421         ss7_link_noalarm(linkset->ss7, linkset->fds[which]);
1422 }
1423
1424 /*!
1425  * \brief Setup and add a SS7 link channel.
1426  * \since 1.8
1427  *
1428  * \param linkset Controlling linkset for the channel.
1429  * \param which Link index of the signaling channel.
1430  * \param ss7type Switch type of the linkset
1431  * \param transport Signaling transport of channel.
1432  * \param inalarm Non-zero if the channel is in alarm.
1433  * \param networkindicator User configuration parameter.
1434  * \param pointcode User configuration parameter.
1435  * \param adjpointcode User configuration parameter.
1436  *
1437  * \retval 0 on success.
1438  * \retval -1 on error.
1439  */
1440 int sig_ss7_add_sigchan(struct sig_ss7_linkset *linkset, int which, int ss7type, int transport, int inalarm, int networkindicator, int pointcode, int adjpointcode)
1441 {
1442         if (!linkset->ss7) {
1443                 linkset->type = ss7type;
1444                 linkset->ss7 = ss7_new(ss7type);
1445                 if (!linkset->ss7) {
1446                         ast_log(LOG_ERROR, "Can't create new SS7!\n");
1447                         return -1;
1448                 }
1449         }
1450
1451         ss7_set_network_ind(linkset->ss7, networkindicator);
1452         ss7_set_pc(linkset->ss7, pointcode);
1453
1454         if (ss7_add_link(linkset->ss7, transport, linkset->fds[which])) {
1455                 ast_log(LOG_WARNING, "Could not add SS7 link!\n");
1456         }
1457
1458         if (inalarm) {
1459                 linkset->linkstate[which] = LINKSTATE_DOWN | LINKSTATE_INALARM;
1460                 ss7_link_alarm(linkset->ss7, linkset->fds[which]);
1461         } else {
1462                 linkset->linkstate[which] = LINKSTATE_DOWN;
1463                 ss7_link_noalarm(linkset->ss7, linkset->fds[which]);
1464         }
1465
1466         ss7_set_adjpc(linkset->ss7, linkset->fds[which], adjpointcode);
1467
1468         return 0;
1469 }
1470
1471 /*!
1472  * \brief Determine if the specified channel is available for an outgoing call.
1473  * \since 1.8
1474  *
1475  * \param p Signaling private structure pointer.
1476  *
1477  * \retval TRUE if the channel is available.
1478  */
1479 int sig_ss7_available(struct sig_ss7_chan *p)
1480 {
1481         int available;
1482
1483         if (!p->ss7) {
1484                 /* Something is wrong here.  A SS7 channel without the ss7 pointer? */
1485                 return 0;
1486         }
1487
1488         /* Only have to deal with the linkset lock. */
1489         ast_mutex_lock(&p->ss7->lock);
1490         available = sig_ss7_is_chan_available(p);
1491         if (available) {
1492                 p->call_level = SIG_SS7_CALL_LEVEL_ALLOCATED;
1493         }
1494         ast_mutex_unlock(&p->ss7->lock);
1495
1496         return available;
1497 }
1498
1499 static unsigned char cid_pres2ss7pres(int cid_pres)
1500 {
1501          return (cid_pres >> 5) & 0x03;
1502 }
1503
1504 static unsigned char cid_pres2ss7screen(int cid_pres)
1505 {
1506         return cid_pres & 0x03;
1507 }
1508
1509 /*!
1510  * \brief Dial out using the specified SS7 channel.
1511  * \since 1.8
1512  *
1513  * \param p Signaling private structure pointer.
1514  * \param ast Asterisk channel structure pointer.
1515  * \param rdest Dialstring.
1516  *
1517  * \retval 0 on success.
1518  * \retval -1 on error.
1519  */
1520 int sig_ss7_call(struct sig_ss7_chan *p, struct ast_channel *ast, const char *rdest)
1521 {
1522         char ss7_called_nai;
1523         int called_nai_strip;
1524         char ss7_calling_nai;
1525         int calling_nai_strip;
1526         const char *charge_str = NULL;
1527         const char *gen_address = NULL;
1528         const char *gen_digits = NULL;
1529         const char *gen_dig_type = NULL;
1530         const char *gen_dig_scheme = NULL;
1531         const char *gen_name = NULL;
1532         const char *jip_digits = NULL;
1533         const char *lspi_ident = NULL;
1534         const char *rlt_flag = NULL;
1535         const char *call_ref_id = NULL;
1536         const char *call_ref_pc = NULL;
1537         const char *send_far = NULL;
1538         char *c;
1539         char *l;
1540         char dest[256];
1541
1542         ast_copy_string(dest, rdest, sizeof(dest));
1543
1544         c = strchr(dest, '/');
1545         if (c) {
1546                 c++;
1547         } else {
1548                 c = "";
1549         }
1550         if (strlen(c) < p->stripmsd) {
1551                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1552                 return -1;
1553         }
1554
1555         if (!p->hidecallerid) {
1556                 l = ast_channel_connected(ast)->id.number.valid ? ast_channel_connected(ast)->id.number.str : NULL;
1557         } else {
1558                 l = NULL;
1559         }
1560
1561         ss7_grab(p, p->ss7);
1562
1563         if (p->call_level != SIG_SS7_CALL_LEVEL_ALLOCATED) {
1564                 /* Call collision before sending IAM.  Abort call. */
1565                 ss7_rel(p->ss7);
1566                 return -1;
1567         }
1568
1569         p->ss7call = isup_new_call(p->ss7->ss7);
1570         if (!p->ss7call) {
1571                 ss7_rel(p->ss7);
1572                 ast_log(LOG_ERROR, "Unable to allocate new SS7 call!\n");
1573                 return -1;
1574         }
1575
1576         called_nai_strip = 0;
1577         ss7_called_nai = p->ss7->called_nai;
1578         if (ss7_called_nai == SS7_NAI_DYNAMIC) { /* compute dynamically */
1579                 if (strncmp(c + p->stripmsd, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
1580                         called_nai_strip = strlen(p->ss7->internationalprefix);
1581                         ss7_called_nai = SS7_NAI_INTERNATIONAL;
1582                 } else if (strncmp(c + p->stripmsd, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
1583                         called_nai_strip = strlen(p->ss7->nationalprefix);
1584                         ss7_called_nai = SS7_NAI_NATIONAL;
1585                 } else {
1586                         ss7_called_nai = SS7_NAI_SUBSCRIBER;
1587                 }
1588         }
1589         isup_set_called(p->ss7call, c + p->stripmsd + called_nai_strip, ss7_called_nai, p->ss7->ss7);
1590
1591         calling_nai_strip = 0;
1592         ss7_calling_nai = p->ss7->calling_nai;
1593         if ((l != NULL) && (ss7_calling_nai == SS7_NAI_DYNAMIC)) { /* compute dynamically */
1594                 if (strncmp(l, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
1595                         calling_nai_strip = strlen(p->ss7->internationalprefix);
1596                         ss7_calling_nai = SS7_NAI_INTERNATIONAL;
1597                 } else if (strncmp(l, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
1598                         calling_nai_strip = strlen(p->ss7->nationalprefix);
1599                         ss7_calling_nai = SS7_NAI_NATIONAL;
1600                 } else {
1601                         ss7_calling_nai = SS7_NAI_SUBSCRIBER;
1602                 }
1603         }
1604         isup_set_calling(p->ss7call, l ? (l + calling_nai_strip) : NULL, ss7_calling_nai,
1605                 p->use_callingpres ? cid_pres2ss7pres(ast_channel_connected(ast)->id.number.presentation) : (l ? SS7_PRESENTATION_ALLOWED : SS7_PRESENTATION_RESTRICTED),
1606                 p->use_callingpres ? cid_pres2ss7screen(ast_channel_connected(ast)->id.number.presentation) : SS7_SCREENING_USER_PROVIDED);
1607
1608         isup_set_oli(p->ss7call, ast_channel_connected(ast)->ani2);
1609         isup_init_call(p->ss7->ss7, p->ss7call, p->cic, p->dpc);
1610
1611         /* Set the charge number if it is set */
1612         charge_str = pbx_builtin_getvar_helper(ast, "SS7_CHARGE_NUMBER");
1613         if (charge_str)
1614                 isup_set_charge(p->ss7call, charge_str, SS7_ANI_CALLING_PARTY_SUB_NUMBER, 0x10);
1615
1616         gen_address = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_ADDRESS");
1617         if (gen_address)
1618                 isup_set_gen_address(p->ss7call, gen_address, p->gen_add_nai,p->gen_add_pres_ind, p->gen_add_num_plan,p->gen_add_type); /* need to add some types here for NAI,PRES,TYPE */
1619
1620         gen_digits = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGITS");
1621         gen_dig_type = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGTYPE");
1622         gen_dig_scheme = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGSCHEME");
1623         if (gen_digits)
1624                 isup_set_gen_digits(p->ss7call, gen_digits, atoi(gen_dig_type), atoi(gen_dig_scheme));
1625
1626         gen_name = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_NAME");
1627         if (gen_name)
1628                 isup_set_generic_name(p->ss7call, gen_name, GEN_NAME_TYPE_CALLING_NAME, GEN_NAME_AVAIL_AVAILABLE, GEN_NAME_PRES_ALLOWED);
1629
1630         jip_digits = pbx_builtin_getvar_helper(ast, "SS7_JIP");
1631         if (jip_digits)
1632                 isup_set_jip_digits(p->ss7call, jip_digits);
1633
1634         lspi_ident = pbx_builtin_getvar_helper(ast, "SS7_LSPI_IDENT");
1635         if (lspi_ident)
1636                 isup_set_lspi(p->ss7call, lspi_ident, 0x18, 0x7, 0x00);
1637
1638         rlt_flag = pbx_builtin_getvar_helper(ast, "SS7_RLT_ON");
1639         if ((rlt_flag) && ((strncmp("NO", rlt_flag, strlen(rlt_flag))) != 0 )) {
1640                 isup_set_lspi(p->ss7call, rlt_flag, 0x18, 0x7, 0x00); /* Setting for Nortel DMS-250/500 */
1641         }
1642
1643         call_ref_id = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_IDENT");
1644         call_ref_pc = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_PC");
1645         if (call_ref_id && call_ref_pc) {
1646                 isup_set_callref(p->ss7call, atoi(call_ref_id),
1647                                  call_ref_pc ? atoi(call_ref_pc) : 0);
1648         }
1649
1650         send_far = pbx_builtin_getvar_helper(ast, "SS7_SEND_FAR");
1651         if ((send_far) && ((strncmp("NO", send_far, strlen(send_far))) != 0 ))
1652                 (isup_far(p->ss7->ss7, p->ss7call));
1653
1654         p->call_level = SIG_SS7_CALL_LEVEL_SETUP;
1655         isup_iam(p->ss7->ss7, p->ss7call);
1656         sig_ss7_set_dialing(p, 1);
1657         ast_setstate(ast, AST_STATE_DIALING);
1658         ss7_rel(p->ss7);
1659         return 0;
1660 }
1661
1662 /*!
1663  * \brief SS7 hangup channel.
1664  * \since 1.8
1665  *
1666  * \param p Signaling private structure pointer.
1667  * \param ast Asterisk channel structure pointer.
1668  *
1669  * \retval 0 on success.
1670  * \retval -1 on error.
1671  */
1672 int sig_ss7_hangup(struct sig_ss7_chan *p, struct ast_channel *ast)
1673 {
1674         int res = 0;
1675
1676         if (!ast_channel_tech_pvt(ast)) {
1677                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1678                 return 0;
1679         }
1680
1681         p->owner = NULL;
1682         sig_ss7_set_dialing(p, 0);
1683         sig_ss7_set_outgoing(p, 0);
1684         p->progress = 0;
1685         p->rlt = 0;
1686         p->exten[0] = '\0';
1687         /* Perform low level hangup if no owner left */
1688         ss7_grab(p, p->ss7);
1689         p->call_level = SIG_SS7_CALL_LEVEL_IDLE;
1690         if (p->ss7call) {
1691                 if (!p->alreadyhungup) {
1692                         const char *cause = pbx_builtin_getvar_helper(ast,"SS7_CAUSE");
1693                         int icause = ast_channel_hangupcause(ast) ? ast_channel_hangupcause(ast) : -1;
1694
1695                         if (cause) {
1696                                 if (atoi(cause)) {
1697                                         icause = atoi(cause);
1698                                 }
1699                         }
1700                         isup_rel(p->ss7->ss7, p->ss7call, icause);
1701                         p->alreadyhungup = 1;
1702                 }
1703         }
1704         ss7_rel(p->ss7);
1705
1706         return res;
1707 }
1708
1709 /*!
1710  * \brief SS7 answer channel.
1711  * \since 1.8
1712  *
1713  * \param p Signaling private structure pointer.
1714  * \param ast Asterisk channel structure pointer.
1715  *
1716  * \retval 0 on success.
1717  * \retval -1 on error.
1718  */
1719 int sig_ss7_answer(struct sig_ss7_chan *p, struct ast_channel *ast)
1720 {
1721         int res;
1722
1723         ss7_grab(p, p->ss7);
1724         if (p->call_level < SIG_SS7_CALL_LEVEL_CONNECT) {
1725                 p->call_level = SIG_SS7_CALL_LEVEL_CONNECT;
1726         }
1727         sig_ss7_open_media(p);
1728         res = isup_anm(p->ss7->ss7, p->ss7call);
1729         ss7_rel(p->ss7);
1730         return res;
1731 }
1732
1733 /*!
1734  * \brief Fix up a channel:  If a channel is consumed, this is called.  Basically update any ->owner links.
1735  * \since 1.8
1736  *
1737  * \param oldchan Old channel pointer to replace.
1738  * \param newchan New channel pointer to set.
1739  * \param pchan Signaling private structure pointer.
1740  *
1741  * \return Nothing
1742  */
1743 void sig_ss7_fixup(struct ast_channel *oldchan, struct ast_channel *newchan, struct sig_ss7_chan *pchan)
1744 {
1745         if (pchan->owner == oldchan) {
1746                 pchan->owner = newchan;
1747         }
1748 }
1749
1750 /*!
1751  * \brief SS7 answer channel.
1752  * \since 1.8
1753  *
1754  * \param p Signaling private structure pointer.
1755  * \param chan Asterisk channel structure pointer.
1756  * \param condition AST control frame subtype.
1757  * \param data AST control frame payload contents.
1758  * \param datalen Length of payload contents.
1759  *
1760  * \retval 0 on success.
1761  * \retval -1 on error or indication condition not handled.
1762  */
1763 int sig_ss7_indicate(struct sig_ss7_chan *p, struct ast_channel *chan, int condition, const void *data, size_t datalen)
1764 {
1765         int res = -1;
1766
1767         switch (condition) {
1768         case AST_CONTROL_BUSY:
1769                 if (p->call_level < SIG_SS7_CALL_LEVEL_CONNECT) {
1770                         ast_channel_hangupcause_set(chan, AST_CAUSE_USER_BUSY);
1771                         ast_softhangup_nolock(chan, AST_SOFTHANGUP_DEV);
1772                         res = 0;
1773                         break;
1774                 }
1775                 res = sig_ss7_play_tone(p, SIG_SS7_TONE_BUSY);
1776                 break;
1777         case AST_CONTROL_RINGING:
1778                 ss7_grab(p, p->ss7);
1779                 if (p->call_level < SIG_SS7_CALL_LEVEL_ALERTING && !p->outgoing) {
1780                         p->call_level = SIG_SS7_CALL_LEVEL_ALERTING;
1781                         if ((isup_far(p->ss7->ss7, p->ss7call)) != -1) {
1782                                 p->rlt = 1;
1783                         }
1784
1785                         /* No need to send CPG if call will be RELEASE */
1786                         if (p->rlt != 1) {
1787                                 isup_cpg(p->ss7->ss7, p->ss7call, CPG_EVENT_ALERTING);
1788                         }
1789                 }
1790                 ss7_rel(p->ss7);
1791
1792                 res = sig_ss7_play_tone(p, SIG_SS7_TONE_RINGTONE);
1793
1794                 if (ast_channel_state(chan) != AST_STATE_UP && ast_channel_state(chan) != AST_STATE_RING) {
1795                         ast_setstate(chan, AST_STATE_RINGING);
1796                 }
1797                 break;
1798         case AST_CONTROL_PROCEEDING:
1799                 ast_debug(1,"Received AST_CONTROL_PROCEEDING on %s\n",ast_channel_name(chan));
1800                 ss7_grab(p, p->ss7);
1801                 /* This IF sends the FAR for an answered ALEG call */
1802                 if (ast_channel_state(chan) == AST_STATE_UP && (p->rlt != 1)){
1803                         if ((isup_far(p->ss7->ss7, p->ss7call)) != -1) {
1804                                 p->rlt = 1;
1805                         }
1806                 }
1807
1808                 if (p->call_level < SIG_SS7_CALL_LEVEL_PROCEEDING && !p->outgoing) {
1809                         p->call_level = SIG_SS7_CALL_LEVEL_PROCEEDING;
1810                         isup_acm(p->ss7->ss7, p->ss7call);
1811                 }
1812                 ss7_rel(p->ss7);
1813                 /* don't continue in ast_indicate */
1814                 res = 0;
1815                 break;
1816         case AST_CONTROL_PROGRESS:
1817                 ast_debug(1,"Received AST_CONTROL_PROGRESS on %s\n",ast_channel_name(chan));
1818                 ss7_grab(p, p->ss7);
1819                 if (!p->progress && p->call_level < SIG_SS7_CALL_LEVEL_ALERTING && !p->outgoing) {
1820                         p->progress = 1;/* No need to send inband-information progress again. */
1821                         isup_cpg(p->ss7->ss7, p->ss7call, CPG_EVENT_INBANDINFO);
1822                         ss7_rel(p->ss7);
1823
1824                         /* enable echo canceler here on SS7 calls */
1825                         sig_ss7_set_echocanceller(p, 1);
1826                 } else {
1827                         ss7_rel(p->ss7);
1828                 }
1829                 /* don't continue in ast_indicate */
1830                 res = 0;
1831                 break;
1832         case AST_CONTROL_INCOMPLETE:
1833                 if (p->call_level < SIG_SS7_CALL_LEVEL_CONNECT) {
1834                         ast_channel_hangupcause_set(chan, AST_CAUSE_INVALID_NUMBER_FORMAT);
1835                         ast_softhangup_nolock(chan, AST_SOFTHANGUP_DEV);
1836                         res = 0;
1837                         break;
1838                 }
1839                 /* Wait for DTMF digits to complete the dialed number. */
1840                 res = 0;
1841                 break;
1842         case AST_CONTROL_CONGESTION:
1843                 if (p->call_level < SIG_SS7_CALL_LEVEL_CONNECT) {
1844                         ast_channel_hangupcause_set(chan, AST_CAUSE_CONGESTION);
1845                         ast_softhangup_nolock(chan, AST_SOFTHANGUP_DEV);
1846                         res = 0;
1847                         break;
1848                 }
1849                 res = sig_ss7_play_tone(p, SIG_SS7_TONE_CONGESTION);
1850                 break;
1851         case AST_CONTROL_HOLD:
1852                 ast_moh_start(chan, data, p->mohinterpret);
1853                 break;
1854         case AST_CONTROL_UNHOLD:
1855                 ast_moh_stop(chan);
1856                 break;
1857         case AST_CONTROL_SRCUPDATE:
1858                 res = 0;
1859                 break;
1860         case -1:
1861                 res = sig_ss7_play_tone(p, -1);
1862                 break;
1863         }
1864         return res;
1865 }
1866
1867 /*!
1868  * \brief SS7 channel request.
1869  * \since 1.8
1870  *
1871  * \param p Signaling private structure pointer.
1872  * \param law Companding law preferred
1873  * \param requestor Asterisk channel requesting a channel to dial (Can be NULL)
1874  * \param transfercapability
1875  *
1876  * \retval ast_channel on success.
1877  * \retval NULL on error.
1878  */
1879 struct ast_channel *sig_ss7_request(struct sig_ss7_chan *p, enum sig_ss7_law law, const struct ast_channel *requestor, int transfercapability)
1880 {
1881         struct ast_channel *ast;
1882
1883         /* Companding law is determined by SS7 signaling type. */
1884         if (p->ss7->type == SS7_ITU) {
1885                 law = SIG_SS7_ALAW;
1886         } else {
1887                 law = SIG_SS7_ULAW;
1888         }
1889
1890         sig_ss7_set_outgoing(p, 1);
1891         ast = sig_ss7_new_ast_channel(p, AST_STATE_RESERVED, law, transfercapability, p->exten, requestor);
1892         if (!ast) {
1893                 sig_ss7_set_outgoing(p, 0);
1894
1895                 /* Release the allocated channel.  Only have to deal with the linkset lock. */
1896                 ast_mutex_lock(&p->ss7->lock);
1897                 p->call_level = SIG_SS7_CALL_LEVEL_IDLE;
1898                 ast_mutex_unlock(&p->ss7->lock);
1899         }
1900         return ast;
1901 }
1902
1903 /*!
1904  * \brief Delete the sig_ss7 private channel structure.
1905  * \since 1.8
1906  *
1907  * \param doomed sig_ss7 private channel structure to delete.
1908  *
1909  * \return Nothing
1910  */
1911 void sig_ss7_chan_delete(struct sig_ss7_chan *doomed)
1912 {
1913         ast_free(doomed);
1914 }
1915
1916 #define SIG_SS7_SC_HEADER       "%-4s %4s %-4s %-3s %-3s %-10s %-4s %s\n"
1917 #define SIG_SS7_SC_LINE          "%4d %4d %-4s %-3s %-3s %-10s %-4s %s"
1918 void sig_ss7_cli_show_channels_header(int fd)
1919 {
1920         ast_cli(fd, SIG_SS7_SC_HEADER, "link", "",     "Chan", "Lcl", "Rem", "Call",  "SS7",  "Channel");
1921         ast_cli(fd, SIG_SS7_SC_HEADER, "set",  "Chan", "Idle", "Blk", "Blk", "Level", "Call", "Name");
1922 }
1923
1924 void sig_ss7_cli_show_channels(int fd, struct sig_ss7_linkset *linkset)
1925 {
1926         char line[256];
1927         int idx;
1928         struct sig_ss7_chan *pvt;
1929
1930         ast_mutex_lock(&linkset->lock);
1931         for (idx = 0; idx < linkset->numchans; ++idx) {
1932                 if (!linkset->pvts[idx]) {
1933                         continue;
1934                 }
1935                 pvt = linkset->pvts[idx];
1936                 sig_ss7_lock_private(pvt);
1937                 sig_ss7_lock_owner(linkset, idx);
1938
1939                 snprintf(line, sizeof(line), SIG_SS7_SC_LINE,
1940                         linkset->span,
1941                         pvt->channel,
1942                         sig_ss7_is_chan_available(pvt) ? "Yes" : "No",
1943                         pvt->locallyblocked ? "Yes" : "No",
1944                         pvt->remotelyblocked ? "Yes" : "No",
1945                         sig_ss7_call_level2str(pvt->call_level),
1946                         pvt->ss7call ? "Yes" : "No",
1947                         pvt->owner ? ast_channel_name(pvt->owner) : "");
1948
1949                 if (pvt->owner) {
1950                         ast_channel_unlock(pvt->owner);
1951                 }
1952                 sig_ss7_unlock_private(pvt);
1953
1954                 ast_mutex_unlock(&linkset->lock);
1955                 ast_cli(fd, "%s\n", line);
1956                 ast_mutex_lock(&linkset->lock);
1957         }
1958         ast_mutex_unlock(&linkset->lock);
1959 }
1960
1961 /*!
1962  * \brief Create a new sig_ss7 private channel structure.
1963  * \since 1.8
1964  *
1965  * \param pvt_data Upper layer private data structure.
1966  * \param ss7 Controlling linkset for the channel.
1967  *
1968  * \retval sig_ss7_chan on success.
1969  * \retval NULL on error.
1970  */
1971 struct sig_ss7_chan *sig_ss7_chan_new(void *pvt_data, struct sig_ss7_linkset *ss7)
1972 {
1973         struct sig_ss7_chan *pvt;
1974
1975         pvt = ast_calloc(1, sizeof(*pvt));
1976         if (!pvt) {
1977                 return pvt;
1978         }
1979
1980         pvt->chan_pvt = pvt_data;
1981         pvt->ss7 = ss7;
1982
1983         return pvt;
1984 }
1985
1986 /*!
1987  * \brief Initialize the SS7 linkset control.
1988  * \since 1.8
1989  *
1990  * \param ss7 SS7 linkset control structure.
1991  *
1992  * \return Nothing
1993  */
1994 void sig_ss7_init_linkset(struct sig_ss7_linkset *ss7)
1995 {
1996         int idx;
1997
1998         memset(ss7, 0, sizeof(*ss7));
1999
2000         ast_mutex_init(&ss7->lock);
2001
2002         ss7->master = AST_PTHREADT_NULL;
2003         for (idx = 0; idx < ARRAY_LEN(ss7->fds); ++idx) {
2004                 ss7->fds[idx] = -1;
2005         }
2006 }
2007
2008 /* ------------------------------------------------------------------- */
2009
2010 #endif  /* defined(HAVE_SS7) */
2011 /* end sig_ss7.c */