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