Thu Sep 7 01:03:05 2017

Asterisk developer's documentation


sig_pri.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2009, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief PRI signaling module
00022  *
00023  * \author Matthew Fredrickson <creslin@digium.com>
00024  */
00025 
00026 /*** MODULEINFO
00027    <support_level>core</support_level>
00028  ***/
00029 
00030 #include "asterisk.h"
00031 
00032 #ifdef HAVE_PRI
00033 
00034 #include <errno.h>
00035 #include <ctype.h>
00036 #include <signal.h>
00037 
00038 #include "asterisk/utils.h"
00039 #include "asterisk/options.h"
00040 #include "asterisk/pbx.h"
00041 #include "asterisk/app.h"
00042 #include "asterisk/file.h"
00043 #include "asterisk/callerid.h"
00044 #include "asterisk/say.h"
00045 #include "asterisk/manager.h"
00046 #include "asterisk/astdb.h"
00047 #include "asterisk/causes.h"
00048 #include "asterisk/musiconhold.h"
00049 #include "asterisk/cli.h"
00050 #include "asterisk/transcap.h"
00051 #include "asterisk/features.h"
00052 #include "asterisk/aoc.h"
00053 
00054 #include "sig_pri.h"
00055 #ifndef PRI_EVENT_FACILITY
00056 #error "Upgrade your libpri"
00057 #endif
00058 
00059 /* define this to send PRI user-user information elements */
00060 #undef SUPPORT_USERUSER
00061 
00062 /*!
00063  * Define to make always pick a channel if allowed.  Useful for
00064  * testing channel shifting.
00065  */
00066 //#define ALWAYS_PICK_CHANNEL 1
00067 
00068 /*!
00069  * Define to force a RESTART on a channel that returns a cause
00070  * code of PRI_CAUSE_REQUESTED_CHAN_UNAVAIL(44).  If the cause
00071  * is because of a stuck channel on the peer and the channel is
00072  * always the next channel we pick for an outgoing call then
00073  * this can help.
00074  */
00075 #define FORCE_RESTART_UNAVAIL_CHANS    1
00076 
00077 #if defined(HAVE_PRI_CCSS)
00078 struct sig_pri_cc_agent_prv {
00079    /*! Asterisk span D channel control structure. */
00080    struct sig_pri_span *pri;
00081    /*! CC id value to use with libpri. -1 if invalid. */
00082    long cc_id;
00083    /*! TRUE if CC has been requested and we are waiting for the response. */
00084    unsigned char cc_request_response_pending;
00085 };
00086 
00087 struct sig_pri_cc_monitor_instance {
00088    /*! \brief Asterisk span D channel control structure. */
00089    struct sig_pri_span *pri;
00090    /*! CC id value to use with libpri. (-1 if already canceled). */
00091    long cc_id;
00092    /*! CC core id value. */
00093    int core_id;
00094    /*! Device name(Channel name less sequence number) */
00095    char name[1];
00096 };
00097 
00098 /*! Upper level agent/monitor type name. */
00099 static const char *sig_pri_cc_type_name;
00100 /*! Container of sig_pri monitor instances. */
00101 static struct ao2_container *sig_pri_cc_monitors;
00102 #endif   /* defined(HAVE_PRI_CCSS) */
00103 
00104 static int pri_matchdigittimeout = 3000;
00105 
00106 static int pri_gendigittimeout = 8000;
00107 
00108 #define DCHAN_NOTINALARM  (1 << 0)
00109 #define DCHAN_UP          (1 << 1)
00110 
00111 /* Defines to help decode the encoded event channel id. */
00112 #define PRI_CHANNEL(p)  ((p) & 0xff)
00113 #define PRI_SPAN(p)     (((p) >> 8) & 0xff)
00114 #define PRI_EXPLICIT (1 << 16)
00115 #define PRI_CIS_CALL (1 << 17)   /* Call is using the D channel only. */
00116 #define PRI_HELD_CALL   (1 << 18)
00117 
00118 
00119 #define DCHAN_AVAILABLE (DCHAN_NOTINALARM | DCHAN_UP)
00120 
00121 static int pri_active_dchan_index(struct sig_pri_span *pri);
00122 
00123 static const char *sig_pri_call_level2str(enum sig_pri_call_level level)
00124 {
00125    switch (level) {
00126    case SIG_PRI_CALL_LEVEL_IDLE:
00127       return "Idle";
00128    case SIG_PRI_CALL_LEVEL_SETUP:
00129       return "Setup";
00130    case SIG_PRI_CALL_LEVEL_OVERLAP:
00131       return "Overlap";
00132    case SIG_PRI_CALL_LEVEL_PROCEEDING:
00133       return "Proceeding";
00134    case SIG_PRI_CALL_LEVEL_ALERTING:
00135       return "Alerting";
00136    case SIG_PRI_CALL_LEVEL_DEFER_DIAL:
00137       return "DeferDial";
00138    case SIG_PRI_CALL_LEVEL_CONNECT:
00139       return "Connect";
00140    }
00141    return "Unknown";
00142 }
00143 
00144 static inline void pri_rel(struct sig_pri_span *pri)
00145 {
00146    ast_mutex_unlock(&pri->lock);
00147 }
00148 
00149 static unsigned int PVT_TO_CHANNEL(struct sig_pri_chan *p)
00150 {
00151    int res = (((p)->prioffset) | ((p)->logicalspan << 8) | (p->mastertrunkgroup ? PRI_EXPLICIT : 0));
00152    ast_debug(5, "prioffset: %d mastertrunkgroup: %d logicalspan: %d result: %d\n",
00153       p->prioffset, p->mastertrunkgroup, p->logicalspan, res);
00154 
00155    return res;
00156 }
00157 
00158 static void sig_pri_handle_dchan_exception(struct sig_pri_span *pri, int index)
00159 {
00160    if (pri->calls->handle_dchan_exception)
00161       pri->calls->handle_dchan_exception(pri, index);
00162 }
00163 
00164 static void sig_pri_set_dialing(struct sig_pri_chan *p, int is_dialing)
00165 {
00166    if (p->calls->set_dialing) {
00167       p->calls->set_dialing(p->chan_pvt, is_dialing);
00168    }
00169 }
00170 
00171 static void sig_pri_set_digital(struct sig_pri_chan *p, int is_digital)
00172 {
00173    p->digital = is_digital;
00174    if (p->calls->set_digital) {
00175       p->calls->set_digital(p->chan_pvt, is_digital);
00176    }
00177 }
00178 
00179 static void sig_pri_set_outgoing(struct sig_pri_chan *p, int is_outgoing)
00180 {
00181    p->outgoing = is_outgoing;
00182    if (p->calls->set_outgoing) {
00183       p->calls->set_outgoing(p->chan_pvt, is_outgoing);
00184    }
00185 }
00186 
00187 void sig_pri_set_alarm(struct sig_pri_chan *p, int in_alarm)
00188 {
00189    if (sig_pri_is_alarm_ignored(p->pri)) {
00190       /* Always set not in alarm */
00191       in_alarm = 0;
00192    }
00193 
00194    /*
00195     * Clear the channel restart state when the channel alarm
00196     * changes to prevent the state from getting stuck when the link
00197     * goes down.
00198     */
00199    p->resetting = SIG_PRI_RESET_IDLE;
00200 
00201    p->inalarm = in_alarm;
00202    if (p->calls->set_alarm) {
00203       p->calls->set_alarm(p->chan_pvt, in_alarm);
00204    }
00205 }
00206 
00207 static const char *sig_pri_get_orig_dialstring(struct sig_pri_chan *p)
00208 {
00209    if (p->calls->get_orig_dialstring) {
00210       return p->calls->get_orig_dialstring(p->chan_pvt);
00211    }
00212    ast_log(LOG_ERROR, "get_orig_dialstring callback not defined\n");
00213    return "";
00214 }
00215 
00216 #if defined(HAVE_PRI_CCSS)
00217 static void sig_pri_make_cc_dialstring(struct sig_pri_chan *p, char *buf, size_t buf_size)
00218 {
00219    if (p->calls->make_cc_dialstring) {
00220       p->calls->make_cc_dialstring(p->chan_pvt, buf, buf_size);
00221    } else {
00222       ast_log(LOG_ERROR, "make_cc_dialstring callback not defined\n");
00223       buf[0] = '\0';
00224    }
00225 }
00226 #endif   /* defined(HAVE_PRI_CCSS) */
00227 
00228 static void sig_pri_dial_digits(struct sig_pri_chan *p, const char *dial_string)
00229 {
00230    if (p->calls->dial_digits) {
00231       p->calls->dial_digits(p->chan_pvt, dial_string);
00232    }
00233 }
00234 
00235 /*!
00236  * \internal
00237  * \brief Reevaluate the PRI span device state.
00238  * \since 1.8
00239  *
00240  * \param pri PRI span control structure.
00241  *
00242  * \return Nothing
00243  *
00244  * \note Assumes the pri->lock is already obtained.
00245  */
00246 static void sig_pri_span_devstate_changed(struct sig_pri_span *pri)
00247 {
00248    if (pri->calls->update_span_devstate) {
00249       pri->calls->update_span_devstate(pri);
00250    }
00251 }
00252 
00253 /*!
00254  * \internal
00255  * \brief Set the caller id information in the parent module.
00256  * \since 1.8
00257  *
00258  * \param p sig_pri channel structure.
00259  *
00260  * \return Nothing
00261  */
00262 static void sig_pri_set_caller_id(struct sig_pri_chan *p)
00263 {
00264    struct ast_party_caller caller;
00265 
00266    if (p->calls->set_callerid) {
00267       ast_party_caller_init(&caller);
00268 
00269       caller.id.name.str = p->cid_name;
00270       caller.id.name.presentation = p->callingpres;
00271       caller.id.name.valid = 1;
00272 
00273       caller.id.number.str = p->cid_num;
00274       caller.id.number.plan = p->cid_ton;
00275       caller.id.number.presentation = p->callingpres;
00276       caller.id.number.valid = 1;
00277 
00278       if (!ast_strlen_zero(p->cid_subaddr)) {
00279          caller.id.subaddress.valid = 1;
00280          //caller.id.subaddress.type = 0;/* nsap */
00281          //caller.id.subaddress.odd_even_indicator = 0;
00282          caller.id.subaddress.str = p->cid_subaddr;
00283       }
00284       caller.id.tag = p->user_tag;
00285 
00286       caller.ani.number.str = p->cid_ani;
00287       //caller.ani.number.plan = p->xxx;
00288       //caller.ani.number.presentation = p->xxx;
00289       caller.ani.number.valid = 1;
00290 
00291       caller.ani2 = p->cid_ani2;
00292       p->calls->set_callerid(p->chan_pvt, &caller);
00293    }
00294 }
00295 
00296 /*!
00297  * \internal
00298  * \brief Set the Dialed Number Identifier.
00299  * \since 1.8
00300  *
00301  * \param p sig_pri channel structure.
00302  * \param dnid Dialed Number Identifier string.
00303  *
00304  * \return Nothing
00305  */
00306 static void sig_pri_set_dnid(struct sig_pri_chan *p, const char *dnid)
00307 {
00308    if (p->calls->set_dnid) {
00309       p->calls->set_dnid(p->chan_pvt, dnid);
00310    }
00311 }
00312 
00313 /*!
00314  * \internal
00315  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
00316  * \since 1.8
00317  *
00318  * \param p sig_pri channel structure.
00319  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
00320  *
00321  * \return Nothing
00322  */
00323 static void sig_pri_set_rdnis(struct sig_pri_chan *p, const char *rdnis)
00324 {
00325    if (p->calls->set_rdnis) {
00326       p->calls->set_rdnis(p->chan_pvt, rdnis);
00327    }
00328 }
00329 
00330 static void sig_pri_unlock_private(struct sig_pri_chan *p)
00331 {
00332    if (p->calls->unlock_private)
00333       p->calls->unlock_private(p->chan_pvt);
00334 }
00335 
00336 static void sig_pri_lock_private(struct sig_pri_chan *p)
00337 {
00338    if (p->calls->lock_private)
00339       p->calls->lock_private(p->chan_pvt);
00340 }
00341 
00342 static inline int pri_grab(struct sig_pri_chan *p, struct sig_pri_span *pri)
00343 {
00344    /* Grab the lock first */
00345    while (ast_mutex_trylock(&pri->lock)) {
00346       /* Avoid deadlock */
00347       sig_pri_unlock_private(p);
00348       sched_yield();
00349       sig_pri_lock_private(p);
00350    }
00351    /* Then break the poll */
00352    if (pri->master != AST_PTHREADT_NULL) {
00353       pthread_kill(pri->master, SIGURG);
00354    }
00355    return 0;
00356 }
00357 
00358 /*!
00359  * \internal
00360  * \brief Convert PRI redirecting reason to asterisk version.
00361  * \since 1.8
00362  *
00363  * \param pri_reason PRI redirecting reason.
00364  *
00365  * \return Equivalent asterisk redirecting reason value.
00366  */
00367 static enum AST_REDIRECTING_REASON pri_to_ast_reason(int pri_reason)
00368 {
00369    enum AST_REDIRECTING_REASON ast_reason;
00370 
00371    switch (pri_reason) {
00372    case PRI_REDIR_FORWARD_ON_BUSY:
00373       ast_reason = AST_REDIRECTING_REASON_USER_BUSY;
00374       break;
00375    case PRI_REDIR_FORWARD_ON_NO_REPLY:
00376       ast_reason = AST_REDIRECTING_REASON_NO_ANSWER;
00377       break;
00378    case PRI_REDIR_DEFLECTION:
00379       ast_reason = AST_REDIRECTING_REASON_DEFLECTION;
00380       break;
00381    case PRI_REDIR_UNCONDITIONAL:
00382       ast_reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
00383       break;
00384    case PRI_REDIR_UNKNOWN:
00385    default:
00386       ast_reason = AST_REDIRECTING_REASON_UNKNOWN;
00387       break;
00388    }
00389 
00390    return ast_reason;
00391 }
00392 
00393 /*!
00394  * \internal
00395  * \brief Convert asterisk redirecting reason to PRI version.
00396  * \since 1.8
00397  *
00398  * \param ast_reason Asterisk redirecting reason.
00399  *
00400  * \return Equivalent PRI redirecting reason value.
00401  */
00402 static int ast_to_pri_reason(enum AST_REDIRECTING_REASON ast_reason)
00403 {
00404    int pri_reason;
00405 
00406    switch (ast_reason) {
00407    case AST_REDIRECTING_REASON_USER_BUSY:
00408       pri_reason = PRI_REDIR_FORWARD_ON_BUSY;
00409       break;
00410    case AST_REDIRECTING_REASON_NO_ANSWER:
00411       pri_reason = PRI_REDIR_FORWARD_ON_NO_REPLY;
00412       break;
00413    case AST_REDIRECTING_REASON_UNCONDITIONAL:
00414       pri_reason = PRI_REDIR_UNCONDITIONAL;
00415       break;
00416    case AST_REDIRECTING_REASON_DEFLECTION:
00417       pri_reason = PRI_REDIR_DEFLECTION;
00418       break;
00419    case AST_REDIRECTING_REASON_UNKNOWN:
00420    default:
00421       pri_reason = PRI_REDIR_UNKNOWN;
00422       break;
00423    }
00424 
00425    return pri_reason;
00426 }
00427 
00428 /*!
00429  * \internal
00430  * \brief Convert PRI number presentation to asterisk version.
00431  * \since 1.8
00432  *
00433  * \param pri_presentation PRI number presentation.
00434  *
00435  * \return Equivalent asterisk number presentation value.
00436  */
00437 static int pri_to_ast_presentation(int pri_presentation)
00438 {
00439    int ast_presentation;
00440 
00441    switch (pri_presentation) {
00442    case PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED:
00443       ast_presentation = AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_UNSCREENED;
00444       break;
00445    case PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_PASSED_SCREEN:
00446       ast_presentation = AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_PASSED_SCREEN;
00447       break;
00448    case PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_FAILED_SCREEN:
00449       ast_presentation = AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_FAILED_SCREEN;
00450       break;
00451    case PRI_PRES_ALLOWED | PRI_PRES_NETWORK_NUMBER:
00452       ast_presentation = AST_PRES_ALLOWED | AST_PRES_NETWORK_NUMBER;
00453       break;
00454 
00455    case PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED:
00456       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED;
00457       break;
00458    case PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_PASSED_SCREEN:
00459       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_PASSED_SCREEN;
00460       break;
00461    case PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_FAILED_SCREEN:
00462       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_FAILED_SCREEN;
00463       break;
00464    case PRI_PRES_RESTRICTED | PRI_PRES_NETWORK_NUMBER:
00465       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_NETWORK_NUMBER;
00466       break;
00467 
00468    case PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_UNSCREENED:
00469    case PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_PASSED_SCREEN:
00470    case PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_FAILED_SCREEN:
00471    case PRI_PRES_UNAVAILABLE | PRI_PRES_NETWORK_NUMBER:
00472       ast_presentation = AST_PRES_NUMBER_NOT_AVAILABLE;
00473       break;
00474 
00475    default:
00476       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED;
00477       break;
00478    }
00479 
00480    return ast_presentation;
00481 }
00482 
00483 /*!
00484  * \internal
00485  * \brief Convert asterisk number presentation to PRI version.
00486  * \since 1.8
00487  *
00488  * \param ast_presentation Asterisk number presentation.
00489  *
00490  * \return Equivalent PRI number presentation value.
00491  */
00492 static int ast_to_pri_presentation(int ast_presentation)
00493 {
00494    int pri_presentation;
00495 
00496    switch (ast_presentation) {
00497    case AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_UNSCREENED:
00498       pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED;
00499       break;
00500    case AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_PASSED_SCREEN:
00501       pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_PASSED_SCREEN;
00502       break;
00503    case AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_FAILED_SCREEN:
00504       pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_FAILED_SCREEN;
00505       break;
00506    case AST_PRES_ALLOWED | AST_PRES_NETWORK_NUMBER:
00507       pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_NETWORK_NUMBER;
00508       break;
00509 
00510    case AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED:
00511       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
00512       break;
00513    case AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_PASSED_SCREEN:
00514       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_PASSED_SCREEN;
00515       break;
00516    case AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_FAILED_SCREEN:
00517       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_FAILED_SCREEN;
00518       break;
00519    case AST_PRES_RESTRICTED | AST_PRES_NETWORK_NUMBER:
00520       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_NETWORK_NUMBER;
00521       break;
00522 
00523    case AST_PRES_UNAVAILABLE | AST_PRES_USER_NUMBER_UNSCREENED:
00524    case AST_PRES_UNAVAILABLE | AST_PRES_USER_NUMBER_PASSED_SCREEN:
00525    case AST_PRES_UNAVAILABLE | AST_PRES_USER_NUMBER_FAILED_SCREEN:
00526    case AST_PRES_UNAVAILABLE | AST_PRES_NETWORK_NUMBER:
00527       pri_presentation = PRES_NUMBER_NOT_AVAILABLE;
00528       break;
00529 
00530    default:
00531       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
00532       break;
00533    }
00534 
00535    return pri_presentation;
00536 }
00537 
00538 /*!
00539  * \internal
00540  * \brief Convert PRI name char_set to asterisk version.
00541  * \since 1.8
00542  *
00543  * \param pri_char_set PRI name char_set.
00544  *
00545  * \return Equivalent asterisk name char_set value.
00546  */
00547 static enum AST_PARTY_CHAR_SET pri_to_ast_char_set(int pri_char_set)
00548 {
00549    enum AST_PARTY_CHAR_SET ast_char_set;
00550 
00551    switch (pri_char_set) {
00552    default:
00553    case PRI_CHAR_SET_UNKNOWN:
00554       ast_char_set = AST_PARTY_CHAR_SET_UNKNOWN;
00555       break;
00556    case PRI_CHAR_SET_ISO8859_1:
00557       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_1;
00558       break;
00559    case PRI_CHAR_SET_WITHDRAWN:
00560       ast_char_set = AST_PARTY_CHAR_SET_WITHDRAWN;
00561       break;
00562    case PRI_CHAR_SET_ISO8859_2:
00563       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_2;
00564       break;
00565    case PRI_CHAR_SET_ISO8859_3:
00566       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_3;
00567       break;
00568    case PRI_CHAR_SET_ISO8859_4:
00569       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_4;
00570       break;
00571    case PRI_CHAR_SET_ISO8859_5:
00572       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_5;
00573       break;
00574    case PRI_CHAR_SET_ISO8859_7:
00575       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_7;
00576       break;
00577    case PRI_CHAR_SET_ISO10646_BMPSTRING:
00578       ast_char_set = AST_PARTY_CHAR_SET_ISO10646_BMPSTRING;
00579       break;
00580    case PRI_CHAR_SET_ISO10646_UTF_8STRING:
00581       ast_char_set = AST_PARTY_CHAR_SET_ISO10646_UTF_8STRING;
00582       break;
00583    }
00584 
00585    return ast_char_set;
00586 }
00587 
00588 /*!
00589  * \internal
00590  * \brief Convert asterisk name char_set to PRI version.
00591  * \since 1.8
00592  *
00593  * \param ast_char_set Asterisk name char_set.
00594  *
00595  * \return Equivalent PRI name char_set value.
00596  */
00597 static int ast_to_pri_char_set(enum AST_PARTY_CHAR_SET ast_char_set)
00598 {
00599    int pri_char_set;
00600 
00601    switch (ast_char_set) {
00602    default:
00603    case AST_PARTY_CHAR_SET_UNKNOWN:
00604       pri_char_set = PRI_CHAR_SET_UNKNOWN;
00605       break;
00606    case AST_PARTY_CHAR_SET_ISO8859_1:
00607       pri_char_set = PRI_CHAR_SET_ISO8859_1;
00608       break;
00609    case AST_PARTY_CHAR_SET_WITHDRAWN:
00610       pri_char_set = PRI_CHAR_SET_WITHDRAWN;
00611       break;
00612    case AST_PARTY_CHAR_SET_ISO8859_2:
00613       pri_char_set = PRI_CHAR_SET_ISO8859_2;
00614       break;
00615    case AST_PARTY_CHAR_SET_ISO8859_3:
00616       pri_char_set = PRI_CHAR_SET_ISO8859_3;
00617       break;
00618    case AST_PARTY_CHAR_SET_ISO8859_4:
00619       pri_char_set = PRI_CHAR_SET_ISO8859_4;
00620       break;
00621    case AST_PARTY_CHAR_SET_ISO8859_5:
00622       pri_char_set = PRI_CHAR_SET_ISO8859_5;
00623       break;
00624    case AST_PARTY_CHAR_SET_ISO8859_7:
00625       pri_char_set = PRI_CHAR_SET_ISO8859_7;
00626       break;
00627    case AST_PARTY_CHAR_SET_ISO10646_BMPSTRING:
00628       pri_char_set = PRI_CHAR_SET_ISO10646_BMPSTRING;
00629       break;
00630    case AST_PARTY_CHAR_SET_ISO10646_UTF_8STRING:
00631       pri_char_set = PRI_CHAR_SET_ISO10646_UTF_8STRING;
00632       break;
00633    }
00634 
00635    return pri_char_set;
00636 }
00637 
00638 #if defined(HAVE_PRI_SUBADDR)
00639 /*!
00640  * \internal
00641  * \brief Fill in the asterisk party subaddress from the given PRI party subaddress.
00642  * \since 1.8
00643  *
00644  * \param ast_subaddress Asterisk party subaddress structure.
00645  * \param pri_subaddress PRI party subaddress structure.
00646  *
00647  * \return Nothing
00648  *
00649  */
00650 static void sig_pri_set_subaddress(struct ast_party_subaddress *ast_subaddress, const struct pri_party_subaddress *pri_subaddress)
00651 {
00652    ast_free(ast_subaddress->str);
00653    if (pri_subaddress->length <= 0) {
00654       ast_party_subaddress_init(ast_subaddress);
00655       return;
00656    }
00657 
00658    if (!pri_subaddress->type) {
00659       /* NSAP */
00660       ast_subaddress->str = ast_strdup((char *) pri_subaddress->data);
00661    } else {
00662       char *cnum;
00663       char *ptr;
00664       int x;
00665       int len;
00666 
00667       /* User Specified */
00668       cnum = ast_malloc(2 * pri_subaddress->length + 1);
00669       if (!cnum) {
00670          ast_party_subaddress_init(ast_subaddress);
00671          return;
00672       }
00673 
00674       ptr = cnum;
00675       len = pri_subaddress->length - 1; /* -1 account for zero based indexing */
00676       for (x = 0; x < len; ++x) {
00677          ptr += sprintf(ptr, "%02x", (unsigned)pri_subaddress->data[x]);
00678       }
00679 
00680       if (pri_subaddress->odd_even_indicator) {
00681          /* ODD */
00682          sprintf(ptr, "%01x", (unsigned)((pri_subaddress->data[len]) >> 4));
00683       } else {
00684          /* EVEN */
00685          sprintf(ptr, "%02x", (unsigned)pri_subaddress->data[len]);
00686       }
00687       ast_subaddress->str = cnum;
00688    }
00689    ast_subaddress->type = pri_subaddress->type;
00690    ast_subaddress->odd_even_indicator = pri_subaddress->odd_even_indicator;
00691    ast_subaddress->valid = 1;
00692 }
00693 #endif   /* defined(HAVE_PRI_SUBADDR) */
00694 
00695 #if defined(HAVE_PRI_SUBADDR)
00696 static unsigned char ast_pri_pack_hex_char(char c)
00697 {
00698    unsigned char res;
00699 
00700    if (c < '0') {
00701       res = 0;
00702    } else if (c < ('9' + 1)) {
00703       res = c - '0';
00704    } else if (c < 'A') {
00705       res = 0;
00706    } else if (c < ('F' + 1)) {
00707       res = c - 'A' + 10;
00708    } else if (c < 'a') {
00709       res = 0;
00710    } else if (c < ('f' + 1)) {
00711       res = c - 'a' + 10;
00712    } else {
00713       res = 0;
00714    }
00715    return res;
00716 }
00717 #endif   /* defined(HAVE_PRI_SUBADDR) */
00718 
00719 #if defined(HAVE_PRI_SUBADDR)
00720 /*!
00721  * \internal
00722  * \brief Convert a null terminated hexadecimal string to a packed hex byte array.
00723  * \details left justified, with 0 padding if odd length.
00724  * \since 1.8
00725  *
00726  * \param dst pointer to packed byte array.
00727  * \param src pointer to null terminated hexadecimal string.
00728  * \param maxlen destination array size.
00729  *
00730  * \return Length of byte array
00731  *
00732  * \note The dst is not an ASCIIz string.
00733  * \note The src is an ASCIIz hex string.
00734  */
00735 static int ast_pri_pack_hex_string(unsigned char *dst, char *src, int maxlen)
00736 {
00737    int res = 0;
00738    int len = strlen(src);
00739 
00740    if (len > (2 * maxlen)) {
00741       len = 2 * maxlen;
00742    }
00743 
00744    res = len / 2 + len % 2;
00745 
00746    while (len > 1) {
00747       *dst = ast_pri_pack_hex_char(*src) << 4;
00748       src++;
00749       *dst |= ast_pri_pack_hex_char(*src);
00750       dst++, src++;
00751       len -= 2;
00752    }
00753    if (len) { /* 1 left */
00754       *dst = ast_pri_pack_hex_char(*src) << 4;
00755    }
00756    return res;
00757 }
00758 #endif   /* defined(HAVE_PRI_SUBADDR) */
00759 
00760 #if defined(HAVE_PRI_SUBADDR)
00761 /*!
00762  * \internal
00763  * \brief Fill in the PRI party subaddress from the given asterisk party subaddress.
00764  * \since 1.8
00765  *
00766  * \param pri_subaddress PRI party subaddress structure.
00767  * \param ast_subaddress Asterisk party subaddress structure.
00768  *
00769  * \return Nothing
00770  *
00771  * \note Assumes that pri_subaddress has been previously memset to zero.
00772  */
00773 static void sig_pri_party_subaddress_from_ast(struct pri_party_subaddress *pri_subaddress, const struct ast_party_subaddress *ast_subaddress)
00774 {
00775    if (ast_subaddress->valid && !ast_strlen_zero(ast_subaddress->str)) {
00776       pri_subaddress->type = ast_subaddress->type;
00777       if (!ast_subaddress->type) {
00778          /* 0 = NSAP */
00779          ast_copy_string((char *) pri_subaddress->data, ast_subaddress->str,
00780             sizeof(pri_subaddress->data));
00781          pri_subaddress->length = strlen((char *) pri_subaddress->data);
00782          pri_subaddress->odd_even_indicator = 0;
00783          pri_subaddress->valid = 1;
00784       } else {
00785          /* 2 = User Specified */
00786          /*
00787           * Copy HexString to packed HexData,
00788           * if odd length then right pad trailing byte with 0
00789           */
00790          int length = ast_pri_pack_hex_string(pri_subaddress->data,
00791             ast_subaddress->str, sizeof(pri_subaddress->data));
00792 
00793          pri_subaddress->length = length; /* packed data length */
00794 
00795          length = strlen(ast_subaddress->str);
00796          if (length > 2 * sizeof(pri_subaddress->data)) {
00797             pri_subaddress->odd_even_indicator = 0;
00798          } else {
00799             pri_subaddress->odd_even_indicator = (length & 1);
00800          }
00801          pri_subaddress->valid = 1;
00802       }
00803    }
00804 }
00805 #endif   /* defined(HAVE_PRI_SUBADDR) */
00806 
00807 /*!
00808  * \internal
00809  * \brief Fill in the PRI party name from the given asterisk party name.
00810  * \since 1.8
00811  *
00812  * \param pri_name PRI party name structure.
00813  * \param ast_name Asterisk party name structure.
00814  *
00815  * \return Nothing
00816  *
00817  * \note Assumes that pri_name has been previously memset to zero.
00818  */
00819 static void sig_pri_party_name_from_ast(struct pri_party_name *pri_name, const struct ast_party_name *ast_name)
00820 {
00821    if (!ast_name->valid) {
00822       return;
00823    }
00824    pri_name->valid = 1;
00825    pri_name->presentation = ast_to_pri_presentation(ast_name->presentation);
00826    pri_name->char_set = ast_to_pri_char_set(ast_name->char_set);
00827    if (!ast_strlen_zero(ast_name->str)) {
00828       ast_copy_string(pri_name->str, ast_name->str, sizeof(pri_name->str));
00829    }
00830 }
00831 
00832 /*!
00833  * \internal
00834  * \brief Fill in the PRI party number from the given asterisk party number.
00835  * \since 1.8
00836  *
00837  * \param pri_number PRI party number structure.
00838  * \param ast_number Asterisk party number structure.
00839  *
00840  * \return Nothing
00841  *
00842  * \note Assumes that pri_number has been previously memset to zero.
00843  */
00844 static void sig_pri_party_number_from_ast(struct pri_party_number *pri_number, const struct ast_party_number *ast_number)
00845 {
00846    if (!ast_number->valid) {
00847       return;
00848    }
00849    pri_number->valid = 1;
00850    pri_number->presentation = ast_to_pri_presentation(ast_number->presentation);
00851    pri_number->plan = ast_number->plan;
00852    if (!ast_strlen_zero(ast_number->str)) {
00853       ast_copy_string(pri_number->str, ast_number->str, sizeof(pri_number->str));
00854    }
00855 }
00856 
00857 /*!
00858  * \internal
00859  * \brief Fill in the PRI party id from the given asterisk party id.
00860  * \since 1.8
00861  *
00862  * \param pri_id PRI party id structure.
00863  * \param ast_id Asterisk party id structure.
00864  *
00865  * \return Nothing
00866  *
00867  * \note Assumes that pri_id has been previously memset to zero.
00868  */
00869 static void sig_pri_party_id_from_ast(struct pri_party_id *pri_id, const struct ast_party_id *ast_id)
00870 {
00871    sig_pri_party_name_from_ast(&pri_id->name, &ast_id->name);
00872    sig_pri_party_number_from_ast(&pri_id->number, &ast_id->number);
00873 #if defined(HAVE_PRI_SUBADDR)
00874    sig_pri_party_subaddress_from_ast(&pri_id->subaddress, &ast_id->subaddress);
00875 #endif   /* defined(HAVE_PRI_SUBADDR) */
00876 }
00877 
00878 /*!
00879  * \internal
00880  * \brief Update the PRI redirecting information for the current call.
00881  * \since 1.8
00882  *
00883  * \param pvt sig_pri private channel structure.
00884  * \param ast Asterisk channel
00885  *
00886  * \return Nothing
00887  *
00888  * \note Assumes that the PRI lock is already obtained.
00889  */
00890 static void sig_pri_redirecting_update(struct sig_pri_chan *pvt, struct ast_channel *ast)
00891 {
00892    struct pri_party_redirecting pri_redirecting;
00893 
00894 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
00895 
00896    memset(&pri_redirecting, 0, sizeof(pri_redirecting));
00897    sig_pri_party_id_from_ast(&pri_redirecting.from, &ast->redirecting.from);
00898    sig_pri_party_id_from_ast(&pri_redirecting.to, &ast->redirecting.to);
00899    pri_redirecting.count = ast->redirecting.count;
00900    pri_redirecting.reason = ast_to_pri_reason(ast->redirecting.reason);
00901 
00902    pri_redirecting_update(pvt->pri->pri, pvt->call, &pri_redirecting);
00903 }
00904 
00905 /*!
00906  * \internal
00907  * \brief Reset DTMF detector.
00908  * \since 1.8
00909  *
00910  * \param p sig_pri channel structure.
00911  *
00912  * \return Nothing
00913  */
00914 static void sig_pri_dsp_reset_and_flush_digits(struct sig_pri_chan *p)
00915 {
00916    if (p->calls->dsp_reset_and_flush_digits) {
00917       p->calls->dsp_reset_and_flush_digits(p->chan_pvt);
00918    }
00919 }
00920 
00921 static int sig_pri_set_echocanceller(struct sig_pri_chan *p, int enable)
00922 {
00923    if (p->calls->set_echocanceller)
00924       return p->calls->set_echocanceller(p->chan_pvt, enable);
00925    else
00926       return -1;
00927 }
00928 
00929 static void sig_pri_fixup_chans(struct sig_pri_chan *old_chan, struct sig_pri_chan *new_chan)
00930 {
00931    if (old_chan->calls->fixup_chans)
00932       old_chan->calls->fixup_chans(old_chan->chan_pvt, new_chan->chan_pvt);
00933 }
00934 
00935 static int sig_pri_play_tone(struct sig_pri_chan *p, enum sig_pri_tone tone)
00936 {
00937    if (p->calls->play_tone)
00938       return p->calls->play_tone(p->chan_pvt, tone);
00939    else
00940       return -1;
00941 }
00942 
00943 static struct ast_channel *sig_pri_new_ast_channel(struct sig_pri_chan *p, int state, enum sig_pri_law law, int transfercapability, char *exten, const struct ast_channel *requestor)
00944 {
00945    struct ast_channel *c;
00946 
00947    if (p->calls->new_ast_channel) {
00948       c = p->calls->new_ast_channel(p->chan_pvt, state, law, exten, requestor);
00949    } else {
00950       return NULL;
00951    }
00952    if (!c) {
00953       return NULL;
00954    }
00955 
00956    if (!p->owner)
00957       p->owner = c;
00958    p->isidlecall = 0;
00959    p->alreadyhungup = 0;
00960    c->transfercapability = transfercapability;
00961    pbx_builtin_setvar_helper(c, "TRANSFERCAPABILITY",
00962       ast_transfercapability2str(transfercapability));
00963    if (transfercapability & AST_TRANS_CAP_DIGITAL) {
00964       sig_pri_set_digital(p, 1);
00965    }
00966    if (p->pri) {
00967       ast_mutex_lock(&p->pri->lock);
00968       sig_pri_span_devstate_changed(p->pri);
00969       ast_mutex_unlock(&p->pri->lock);
00970    }
00971 
00972    return c;
00973 }
00974 
00975 /*!
00976  * \internal
00977  * \brief Open the PRI channel media path.
00978  * \since 1.8
00979  *
00980  * \param p Channel private control structure.
00981  *
00982  * \return Nothing
00983  */
00984 static void sig_pri_open_media(struct sig_pri_chan *p)
00985 {
00986    if (p->no_b_channel) {
00987       return;
00988    }
00989 
00990    if (p->calls->open_media) {
00991       p->calls->open_media(p->chan_pvt);
00992    }
00993 }
00994 
00995 /*!
00996  * \internal
00997  * \brief Post an AMI B channel association event.
00998  * \since 1.8
00999  *
01000  * \param p Channel private control structure.
01001  *
01002  * \note Assumes the private and owner are locked.
01003  *
01004  * \return Nothing
01005  */
01006 static void sig_pri_ami_channel_event(struct sig_pri_chan *p)
01007 {
01008    if (p->calls->ami_channel_event) {
01009       p->calls->ami_channel_event(p->chan_pvt, p->owner);
01010    }
01011 }
01012 
01013 struct ast_channel *sig_pri_request(struct sig_pri_chan *p, enum sig_pri_law law, const struct ast_channel *requestor, int transfercapability)
01014 {
01015    struct ast_channel *ast;
01016 
01017    ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
01018 
01019    sig_pri_set_outgoing(p, 1);
01020    ast = sig_pri_new_ast_channel(p, AST_STATE_RESERVED, law, transfercapability, p->exten, requestor);
01021    if (!ast) {
01022       sig_pri_set_outgoing(p, 0);
01023    }
01024    return ast;
01025 }
01026 
01027 int pri_is_up(struct sig_pri_span *pri)
01028 {
01029    int x;
01030    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
01031       if (pri->dchanavail[x] == DCHAN_AVAILABLE)
01032          return 1;
01033    }
01034    return 0;
01035 }
01036 
01037 static const char *pri_order(int level)
01038 {
01039    switch (level) {
01040    case 0:
01041       return "Primary";
01042    case 1:
01043       return "Secondary";
01044    case 2:
01045       return "Tertiary";
01046    case 3:
01047       return "Quaternary";
01048    default:
01049       return "<Unknown>";
01050    }
01051 }
01052 
01053 /* Returns index of the active dchan */
01054 static int pri_active_dchan_index(struct sig_pri_span *pri)
01055 {
01056    int x;
01057 
01058    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
01059       if ((pri->dchans[x] == pri->pri))
01060          return x;
01061    }
01062 
01063    ast_log(LOG_WARNING, "No active dchan found!\n");
01064    return -1;
01065 }
01066 
01067 static void pri_find_dchan(struct sig_pri_span *pri)
01068 {
01069    struct pri *old;
01070    int oldslot = -1;
01071    int newslot = -1;
01072    int idx;
01073 
01074    old = pri->pri;
01075    for (idx = 0; idx < SIG_PRI_NUM_DCHANS; ++idx) {
01076       if (!pri->dchans[idx]) {
01077          /* No more D channels defined on the span. */
01078          break;
01079       }
01080       if (pri->dchans[idx] == old) {
01081          oldslot = idx;
01082       }
01083       if (newslot < 0 && pri->dchanavail[idx] == DCHAN_AVAILABLE) {
01084          newslot = idx;
01085       }
01086    }
01087    /* At this point, idx is a count of how many D-channels are defined on the span. */
01088 
01089    if (1 < idx) {
01090       /* We have several D-channels defined on the span.  (NFAS PRI setup) */
01091       if (newslot < 0) {
01092          /* No D-channels available.  Default to the primary D-channel. */
01093          newslot = 0;
01094 
01095          if (!pri->no_d_channels) {
01096             pri->no_d_channels = 1;
01097             if (old && oldslot != newslot) {
01098                ast_log(LOG_WARNING,
01099                   "Span %d: No D-channels up!  Switching selected D-channel from %s to %s.\n",
01100                   pri->span, pri_order(oldslot), pri_order(newslot));
01101             } else {
01102                ast_log(LOG_WARNING, "Span %d: No D-channels up!\n", pri->span);
01103             }
01104          }
01105       } else {
01106          pri->no_d_channels = 0;
01107       }
01108       if (old && oldslot != newslot) {
01109          ast_log(LOG_NOTICE,
01110             "Switching selected D-channel from %s (fd %d) to %s (fd %d)!\n",
01111             pri_order(oldslot), pri->fds[oldslot],
01112             pri_order(newslot), pri->fds[newslot]);
01113       }
01114    } else {
01115       if (newslot < 0) {
01116          /* The only D-channel is not up. */
01117          newslot = 0;
01118 
01119          if (!pri->no_d_channels) {
01120             pri->no_d_channels = 1;
01121 
01122             /*
01123              * This is annoying to see on non-persistent layer 2
01124              * connections.  Let's not complain in that case.
01125              */
01126             if (pri->sig != SIG_BRI_PTMP) {
01127                ast_log(LOG_WARNING, "Span %d: D-channel is down!\n", pri->span);
01128             }
01129          }
01130       } else {
01131          pri->no_d_channels = 0;
01132       }
01133    }
01134    pri->pri = pri->dchans[newslot];
01135 }
01136 
01137 /*!
01138  * \internal
01139  * \brief Determine if a private channel structure is in use.
01140  * \since 1.8
01141  *
01142  * \param pvt Channel to determine if in use.
01143  *
01144  * \return TRUE if the channel is in use.
01145  */
01146 static int sig_pri_is_chan_in_use(struct sig_pri_chan *pvt)
01147 {
01148    return pvt->owner || pvt->call || pvt->allocated || pvt->inalarm
01149       || pvt->resetting != SIG_PRI_RESET_IDLE;
01150 }
01151 
01152 /*!
01153  * \brief Determine if a private channel structure is available.
01154  * \since 1.8
01155  *
01156  * \param pvt Channel to determine if available.
01157  *
01158  * \return TRUE if the channel is available.
01159  */
01160 int sig_pri_is_chan_available(struct sig_pri_chan *pvt)
01161 {
01162    return !sig_pri_is_chan_in_use(pvt)
01163 #if defined(HAVE_PRI_SERVICE_MESSAGES)
01164       /* And not out-of-service */
01165       && !pvt->service_status
01166 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
01167       ;
01168 }
01169 
01170 /*!
01171  * \internal
01172  * \brief Obtain the sig_pri owner channel lock if the owner exists.
01173  * \since 1.8
01174  *
01175  * \param pri PRI span control structure.
01176  * \param chanpos Channel position in the span.
01177  *
01178  * \note Assumes the pri->lock is already obtained.
01179  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
01180  *
01181  * \return Nothing
01182  */
01183 static void sig_pri_lock_owner(struct sig_pri_span *pri, int chanpos)
01184 {
01185    for (;;) {
01186       if (!pri->pvts[chanpos]->owner) {
01187          /* There is no owner lock to get. */
01188          break;
01189       }
01190       if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
01191          /* We got the lock */
01192          break;
01193       }
01194 
01195       /* Avoid deadlock */
01196       sig_pri_unlock_private(pri->pvts[chanpos]);
01197       DEADLOCK_AVOIDANCE(&pri->lock);
01198       sig_pri_lock_private(pri->pvts[chanpos]);
01199    }
01200 }
01201 
01202 /*!
01203  * \internal
01204  * \brief Queue the given frame onto the owner channel.
01205  * \since 1.8
01206  *
01207  * \param pri PRI span control structure.
01208  * \param chanpos Channel position in the span.
01209  * \param frame Frame to queue onto the owner channel.
01210  *
01211  * \note Assumes the pri->lock is already obtained.
01212  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
01213  *
01214  * \return Nothing
01215  */
01216 static void pri_queue_frame(struct sig_pri_span *pri, int chanpos, struct ast_frame *frame)
01217 {
01218    sig_pri_lock_owner(pri, chanpos);
01219    if (pri->pvts[chanpos]->owner) {
01220       ast_queue_frame(pri->pvts[chanpos]->owner, frame);
01221       ast_channel_unlock(pri->pvts[chanpos]->owner);
01222    }
01223 }
01224 
01225 /*!
01226  * \internal
01227  * \brief Queue a control frame of the specified subclass onto the owner channel.
01228  * \since 1.8
01229  *
01230  * \param pri PRI span control structure.
01231  * \param chanpos Channel position in the span.
01232  * \param subclass Control frame subclass to queue onto the owner channel.
01233  *
01234  * \note Assumes the pri->lock is already obtained.
01235  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
01236  *
01237  * \return Nothing
01238  */
01239 static void pri_queue_control(struct sig_pri_span *pri, int chanpos, int subclass)
01240 {
01241    struct ast_frame f = {AST_FRAME_CONTROL, };
01242    struct sig_pri_chan *p = pri->pvts[chanpos];
01243 
01244    if (p->calls->queue_control) {
01245       p->calls->queue_control(p->chan_pvt, subclass);
01246    }
01247 
01248    f.subclass.integer = subclass;
01249    pri_queue_frame(pri, chanpos, &f);
01250 }
01251 
01252 /*!
01253  * \internal
01254  * \brief Find the channel associated with the libpri call.
01255  * \since 1.10
01256  *
01257  * \param pri PRI span control structure.
01258  * \param call LibPRI opaque call pointer to find.
01259  *
01260  * \note Assumes the pri->lock is already obtained.
01261  *
01262  * \retval array-index into private pointer array on success.
01263  * \retval -1 on error.
01264  */
01265 static int pri_find_principle_by_call(struct sig_pri_span *pri, q931_call *call)
01266 {
01267    int idx;
01268 
01269    if (!call) {
01270       /* Cannot find a call without a call. */
01271       return -1;
01272    }
01273    for (idx = 0; idx < pri->numchans; ++idx) {
01274       if (pri->pvts[idx] && pri->pvts[idx]->call == call) {
01275          /* Found the principle */
01276          return idx;
01277       }
01278    }
01279    return -1;
01280 }
01281 
01282 /*!
01283  * \internal
01284  * \brief Kill the call.
01285  * \since 1.10
01286  *
01287  * \param pri PRI span control structure.
01288  * \param call LibPRI opaque call pointer to find.
01289  * \param cause Reason call was killed.
01290  *
01291  * \note Assumes the pvt->pri->lock is already obtained.
01292  *
01293  * \return Nothing
01294  */
01295 static void sig_pri_kill_call(struct sig_pri_span *pri, q931_call *call, int cause)
01296 {
01297    int chanpos;
01298 
01299    chanpos = pri_find_principle_by_call(pri, call);
01300    if (chanpos < 0) {
01301       pri_hangup(pri->pri, call, cause);
01302       return;
01303    }
01304    sig_pri_lock_private(pri->pvts[chanpos]);
01305    if (!pri->pvts[chanpos]->owner) {
01306       pri_hangup(pri->pri, call, cause);
01307       pri->pvts[chanpos]->call = NULL;
01308       sig_pri_unlock_private(pri->pvts[chanpos]);
01309       sig_pri_span_devstate_changed(pri);
01310       return;
01311    }
01312    pri->pvts[chanpos]->owner->hangupcause = cause;
01313    pri_queue_control(pri, chanpos, AST_CONTROL_HANGUP);
01314    sig_pri_unlock_private(pri->pvts[chanpos]);
01315 }
01316 
01317 /*!
01318  * \internal
01319  * \brief Find the private structure for the libpri call.
01320  *
01321  * \param pri PRI span control structure.
01322  * \param channel LibPRI encoded channel ID.
01323  * \param call LibPRI opaque call pointer.
01324  *
01325  * \note Assumes the pri->lock is already obtained.
01326  *
01327  * \retval array-index into private pointer array on success.
01328  * \retval -1 on error.
01329  */
01330 static int pri_find_principle(struct sig_pri_span *pri, int channel, q931_call *call)
01331 {
01332    int x;
01333    int span;
01334    int principle;
01335    int prioffset;
01336 
01337    if (channel < 0) {
01338       /* Channel is not picked yet. */
01339       return -1;
01340    }
01341 
01342    prioffset = PRI_CHANNEL(channel);
01343    if (!prioffset || (channel & PRI_HELD_CALL)) {
01344       if (!call) {
01345          /* Cannot find a call waiting call or held call without a call. */
01346          return -1;
01347       }
01348       principle = -1;
01349       for (x = 0; x < pri->numchans; ++x) {
01350          if (pri->pvts[x]
01351             && pri->pvts[x]->call == call) {
01352             principle = x;
01353             break;
01354          }
01355       }
01356       return principle;
01357    }
01358 
01359    span = PRI_SPAN(channel);
01360    if (!(channel & PRI_EXPLICIT)) {
01361       int index;
01362 
01363       index = pri_active_dchan_index(pri);
01364       if (index == -1) {
01365          return -1;
01366       }
01367       span = pri->dchan_logical_span[index];
01368    }
01369 
01370    principle = -1;
01371    for (x = 0; x < pri->numchans; x++) {
01372       if (pri->pvts[x]
01373          && pri->pvts[x]->prioffset == prioffset
01374          && pri->pvts[x]->logicalspan == span
01375          && !pri->pvts[x]->no_b_channel) {
01376          principle = x;
01377          break;
01378       }
01379    }
01380 
01381    return principle;
01382 }
01383 
01384 /*!
01385  * \internal
01386  * \brief Fixup the private structure associated with the libpri call.
01387  *
01388  * \param pri PRI span control structure.
01389  * \param principle Array-index into private array to move call to if not already there.
01390  * \param call LibPRI opaque call pointer to find if need to move call.
01391  *
01392  * \note Assumes the pri->lock is already obtained.
01393  *
01394  * \retval principle on success.
01395  * \retval -1 on error.
01396  */
01397 static int pri_fixup_principle(struct sig_pri_span *pri, int principle, q931_call *call)
01398 {
01399    int x;
01400 
01401    if (principle < 0 || pri->numchans <= principle) {
01402       /* Out of rannge */
01403       return -1;
01404    }
01405    if (!call) {
01406       /* No call */
01407       return principle;
01408    }
01409    if (pri->pvts[principle] && pri->pvts[principle]->call == call) {
01410       /* Call is already on the specified principle. */
01411       return principle;
01412    }
01413 
01414    /* Find the old principle location. */
01415    for (x = 0; x < pri->numchans; x++) {
01416       struct sig_pri_chan *new_chan;
01417       struct sig_pri_chan *old_chan;
01418 
01419       if (!pri->pvts[x] || pri->pvts[x]->call != call) {
01420          continue;
01421       }
01422 
01423       /* Found our call */
01424       new_chan = pri->pvts[principle];
01425       old_chan = pri->pvts[x];
01426 
01427       /* Get locks to safely move to the new private structure. */
01428       sig_pri_lock_private(old_chan);
01429       sig_pri_lock_owner(pri, x);
01430       sig_pri_lock_private(new_chan);
01431 
01432       ast_verb(3, "Moving call (%s) from channel %d to %d.\n",
01433          old_chan->owner ? old_chan->owner->name : "",
01434          old_chan->channel, new_chan->channel);
01435       if (!sig_pri_is_chan_available(new_chan)) {
01436          ast_log(LOG_WARNING,
01437             "Can't move call (%s) from channel %d to %d.  It is already in use.\n",
01438             old_chan->owner ? old_chan->owner->name : "",
01439             old_chan->channel, new_chan->channel);
01440          sig_pri_unlock_private(new_chan);
01441          if (old_chan->owner) {
01442             ast_channel_unlock(old_chan->owner);
01443          }
01444          sig_pri_unlock_private(old_chan);
01445          return -1;
01446       }
01447 
01448       sig_pri_fixup_chans(old_chan, new_chan);
01449 
01450       /* Fix it all up now */
01451       new_chan->owner = old_chan->owner;
01452       old_chan->owner = NULL;
01453 
01454       new_chan->call = old_chan->call;
01455       old_chan->call = NULL;
01456 
01457       /* Transfer flags from the old channel. */
01458 #if defined(HAVE_PRI_AOC_EVENTS)
01459       new_chan->aoc_s_request_invoke_id_valid = old_chan->aoc_s_request_invoke_id_valid;
01460       new_chan->waiting_for_aoce = old_chan->waiting_for_aoce;
01461       new_chan->holding_aoce = old_chan->holding_aoce;
01462 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
01463       new_chan->alreadyhungup = old_chan->alreadyhungup;
01464       new_chan->isidlecall = old_chan->isidlecall;
01465       new_chan->progress = old_chan->progress;
01466       new_chan->allocated = old_chan->allocated;
01467       new_chan->outgoing = old_chan->outgoing;
01468       new_chan->digital = old_chan->digital;
01469 #if defined(HAVE_PRI_CALL_WAITING)
01470       new_chan->is_call_waiting = old_chan->is_call_waiting;
01471 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
01472 #if defined(HAVE_PRI_SETUP_ACK_INBAND)
01473       new_chan->no_dialed_digits = old_chan->no_dialed_digits;
01474 #endif   /* defined(HAVE_PRI_SETUP_ACK_INBAND) */
01475 
01476 #if defined(HAVE_PRI_AOC_EVENTS)
01477       old_chan->aoc_s_request_invoke_id_valid = 0;
01478       old_chan->waiting_for_aoce = 0;
01479       old_chan->holding_aoce = 0;
01480 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
01481       old_chan->alreadyhungup = 0;
01482       old_chan->isidlecall = 0;
01483       old_chan->progress = 0;
01484       old_chan->allocated = 0;
01485       old_chan->outgoing = 0;
01486       old_chan->digital = 0;
01487 #if defined(HAVE_PRI_CALL_WAITING)
01488       old_chan->is_call_waiting = 0;
01489 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
01490 #if defined(HAVE_PRI_SETUP_ACK_INBAND)
01491       old_chan->no_dialed_digits = 0;
01492 #endif   /* defined(HAVE_PRI_SETUP_ACK_INBAND) */
01493 
01494       /* More stuff to transfer to the new channel. */
01495       new_chan->call_level = old_chan->call_level;
01496       old_chan->call_level = SIG_PRI_CALL_LEVEL_IDLE;
01497 #if defined(HAVE_PRI_REVERSE_CHARGE)
01498       new_chan->reverse_charging_indication = old_chan->reverse_charging_indication;
01499 #endif   /* defined(HAVE_PRI_REVERSE_CHARGE) */
01500 #if defined(HAVE_PRI_SETUP_KEYPAD)
01501       strcpy(new_chan->keypad_digits, old_chan->keypad_digits);
01502 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
01503       strcpy(new_chan->deferred_digits, old_chan->deferred_digits);
01504 #if defined(HAVE_PRI_AOC_EVENTS)
01505       new_chan->aoc_s_request_invoke_id = old_chan->aoc_s_request_invoke_id;
01506       new_chan->aoc_e = old_chan->aoc_e;
01507 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
01508       strcpy(new_chan->user_tag, old_chan->user_tag);
01509 
01510       if (new_chan->no_b_channel) {
01511          /* Copy the real channel configuration to the no B channel interface. */
01512          new_chan->hidecallerid = old_chan->hidecallerid;
01513          new_chan->hidecalleridname = old_chan->hidecalleridname;
01514          new_chan->immediate = old_chan->immediate;
01515          new_chan->priexclusive = old_chan->priexclusive;
01516          new_chan->priindication_oob = old_chan->priindication_oob;
01517          new_chan->use_callerid = old_chan->use_callerid;
01518          new_chan->use_callingpres = old_chan->use_callingpres;
01519          new_chan->stripmsd = old_chan->stripmsd;
01520          strcpy(new_chan->context, old_chan->context);
01521          strcpy(new_chan->mohinterpret, old_chan->mohinterpret);
01522 
01523          /* Become a member of the old channel span/trunk-group. */
01524          new_chan->logicalspan = old_chan->logicalspan;
01525          new_chan->mastertrunkgroup = old_chan->mastertrunkgroup;
01526       } else if (old_chan->no_b_channel) {
01527          /*
01528           * We are transitioning from a held/call-waiting channel to a
01529           * real channel so we need to make sure that the media path is
01530           * open.  (Needed especially if the channel is natively
01531           * bridged.)
01532           */
01533          sig_pri_open_media(new_chan);
01534       }
01535 
01536       if (new_chan->owner) {
01537          sig_pri_ami_channel_event(new_chan);
01538       }
01539 
01540       sig_pri_unlock_private(old_chan);
01541       if (new_chan->owner) {
01542          ast_channel_unlock(new_chan->owner);
01543       }
01544       sig_pri_unlock_private(new_chan);
01545 
01546       return principle;
01547    }
01548    ast_verb(3, "Call specified, but not found.\n");
01549    return -1;
01550 }
01551 
01552 /*!
01553  * \internal
01554  * \brief Find and fixup the private structure associated with the libpri call.
01555  *
01556  * \param pri PRI span control structure.
01557  * \param channel LibPRI encoded channel ID.
01558  * \param call LibPRI opaque call pointer.
01559  *
01560  * \details
01561  * This is a combination of pri_find_principle() and pri_fixup_principle()
01562  * to reduce code redundancy and to make handling several PRI_EVENT_xxx's
01563  * consistent for the current architecture.
01564  *
01565  * \note Assumes the pri->lock is already obtained.
01566  *
01567  * \retval array-index into private pointer array on success.
01568  * \retval -1 on error.
01569  */
01570 static int pri_find_fixup_principle(struct sig_pri_span *pri, int channel, q931_call *call)
01571 {
01572    int chanpos;
01573 
01574    chanpos = pri_find_principle(pri, channel, call);
01575    if (chanpos < 0) {
01576       ast_log(LOG_WARNING, "Span %d: PRI requested channel %d/%d is unconfigured.\n",
01577          pri->span, PRI_SPAN(channel), PRI_CHANNEL(channel));
01578       sig_pri_kill_call(pri, call, PRI_CAUSE_IDENTIFIED_CHANNEL_NOTEXIST);
01579       return -1;
01580    }
01581    chanpos = pri_fixup_principle(pri, chanpos, call);
01582    if (chanpos < 0) {
01583       ast_log(LOG_WARNING, "Span %d: PRI requested channel %d/%d is not available.\n",
01584          pri->span, PRI_SPAN(channel), PRI_CHANNEL(channel));
01585       /*
01586        * Using Q.931 section 5.2.3.1 b) as the reason for picking
01587        * PRI_CAUSE_CHANNEL_UNACCEPTABLE.  Receiving a
01588        * PRI_CAUSE_REQUESTED_CHAN_UNAVAIL would cause us to restart
01589        * that channel (which is not specified by Q.931) and kill some
01590        * other call which would be bad.
01591        */
01592       sig_pri_kill_call(pri, call, PRI_CAUSE_CHANNEL_UNACCEPTABLE);
01593       return -1;
01594    }
01595    return chanpos;
01596 }
01597 
01598 static char * redirectingreason2str(int redirectingreason)
01599 {
01600    switch (redirectingreason) {
01601    case 0:
01602       return "UNKNOWN";
01603    case 1:
01604       return "BUSY";
01605    case 2:
01606       return "NO_REPLY";
01607    case 0xF:
01608       return "UNCONDITIONAL";
01609    default:
01610       return "NOREDIRECT";
01611    }
01612 }
01613 
01614 static char *dialplan2str(int dialplan)
01615 {
01616    if (dialplan == -1) {
01617       return("Dynamically set dialplan in ISDN");
01618    }
01619    return (pri_plan2str(dialplan));
01620 }
01621 
01622 /*!
01623  * \internal
01624  * \brief Apply numbering plan prefix to the given number.
01625  *
01626  * \param buf Buffer to put number into.
01627  * \param size Size of given buffer.
01628  * \param pri PRI span control structure.
01629  * \param number Number to apply numbering plan.
01630  * \param plan Numbering plan to apply.
01631  *
01632  * \return Nothing
01633  */
01634 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_span *pri, const char *number, int plan)
01635 {
01636    switch (plan) {
01637    case PRI_INTERNATIONAL_ISDN:     /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
01638       snprintf(buf, size, "%s%s", pri->internationalprefix, number);
01639       break;
01640    case PRI_NATIONAL_ISDN:       /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
01641       snprintf(buf, size, "%s%s", pri->nationalprefix, number);
01642       break;
01643    case PRI_LOCAL_ISDN:       /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
01644       snprintf(buf, size, "%s%s", pri->localprefix, number);
01645       break;
01646    case PRI_PRIVATE:       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
01647       snprintf(buf, size, "%s%s", pri->privateprefix, number);
01648       break;
01649    case PRI_UNKNOWN:       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
01650       snprintf(buf, size, "%s%s", pri->unknownprefix, number);
01651       break;
01652    default:          /* other Q.931 dialplan => don't twiddle with callingnum */
01653       snprintf(buf, size, "%s", number);
01654       break;
01655    }
01656 }
01657 
01658 /*!
01659  * \internal
01660  * \brief Apply numbering plan prefix to the given number if the number exists.
01661  *
01662  * \param buf Buffer to put number into.
01663  * \param size Size of given buffer.
01664  * \param pri PRI span control structure.
01665  * \param number Number to apply numbering plan.
01666  * \param plan Numbering plan to apply.
01667  *
01668  * \return Nothing
01669  */
01670 static void apply_plan_to_existing_number(char *buf, size_t size, const struct sig_pri_span *pri, const char *number, int plan)
01671 {
01672    /* Make sure a number exists so the prefix isn't placed on an empty string. */
01673    if (ast_strlen_zero(number)) {
01674       if (size) {
01675          *buf = '\0';
01676       }
01677       return;
01678    }
01679    apply_plan_to_number(buf, size, pri, number, plan);
01680 }
01681 
01682 /*!
01683  * \internal
01684  * \brief Restart the next channel we think is idle on the span.
01685  *
01686  * \param pri PRI span control structure.
01687  *
01688  * \note Assumes the pri->lock is already obtained.
01689  *
01690  * \return Nothing
01691  */
01692 static void pri_check_restart(struct sig_pri_span *pri)
01693 {
01694 #if defined(HAVE_PRI_SERVICE_MESSAGES)
01695    unsigned why;
01696 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
01697 
01698    for (++pri->resetpos; pri->resetpos < pri->numchans; ++pri->resetpos) {
01699       if (!pri->pvts[pri->resetpos]
01700          || pri->pvts[pri->resetpos]->no_b_channel
01701          || sig_pri_is_chan_in_use(pri->pvts[pri->resetpos])) {
01702          continue;
01703       }
01704 #if defined(HAVE_PRI_SERVICE_MESSAGES)
01705       why = pri->pvts[pri->resetpos]->service_status;
01706       if (why) {
01707          ast_log(LOG_NOTICE,
01708             "Span %d: channel %d out-of-service (reason: %s), not sending RESTART\n",
01709             pri->span, pri->pvts[pri->resetpos]->channel,
01710             (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
01711          continue;
01712       }
01713 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
01714       break;
01715    }
01716    if (pri->resetpos < pri->numchans) {
01717       /* Mark the channel as resetting and restart it */
01718       pri->pvts[pri->resetpos]->resetting = SIG_PRI_RESET_ACTIVE;
01719       pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
01720    } else {
01721       pri->resetting = 0;
01722       time(&pri->lastreset);
01723       sig_pri_span_devstate_changed(pri);
01724    }
01725 }
01726 
01727 #if defined(HAVE_PRI_CALL_WAITING)
01728 /*!
01729  * \internal
01730  * \brief Init the private channel configuration using the span controller.
01731  * \since 1.8
01732  *
01733  * \param pvt Channel to init the configuration.
01734  * \param pri PRI span control structure.
01735  *
01736  * \note Assumes the pri->lock is already obtained.
01737  *
01738  * \return Nothing
01739  */
01740 static void sig_pri_init_config(struct sig_pri_chan *pvt, struct sig_pri_span *pri)
01741 {
01742    pvt->stripmsd = pri->ch_cfg.stripmsd;
01743    pvt->hidecallerid = pri->ch_cfg.hidecallerid;
01744    pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
01745    pvt->immediate = pri->ch_cfg.immediate;
01746    pvt->priexclusive = pri->ch_cfg.priexclusive;
01747    pvt->priindication_oob = pri->ch_cfg.priindication_oob;
01748    pvt->use_callerid = pri->ch_cfg.use_callerid;
01749    pvt->use_callingpres = pri->ch_cfg.use_callingpres;
01750    ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
01751    ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
01752 
01753    if (pri->calls->init_config) {
01754       pri->calls->init_config(pvt->chan_pvt, pri);
01755    }
01756 }
01757 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
01758 
01759 /*!
01760  * \internal
01761  * \brief Find an empty B-channel interface to use.
01762  *
01763  * \param pri PRI span control structure.
01764  * \param backwards TRUE if the search starts from higher channels.
01765  *
01766  * \note Assumes the pri->lock is already obtained.
01767  *
01768  * \retval array-index into private pointer array on success.
01769  * \retval -1 on error.
01770  */
01771 static int pri_find_empty_chan(struct sig_pri_span *pri, int backwards)
01772 {
01773    int x;
01774    if (backwards)
01775       x = pri->numchans;
01776    else
01777       x = 0;
01778    for (;;) {
01779       if (backwards && (x < 0))
01780          break;
01781       if (!backwards && (x >= pri->numchans))
01782          break;
01783       if (pri->pvts[x]
01784          && !pri->pvts[x]->no_b_channel
01785          && sig_pri_is_chan_available(pri->pvts[x])) {
01786          ast_debug(1, "Found empty available channel %d/%d\n",
01787             pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
01788          return x;
01789       }
01790       if (backwards)
01791          x--;
01792       else
01793          x++;
01794    }
01795    return -1;
01796 }
01797 
01798 #if defined(HAVE_PRI_CALL_HOLD)
01799 /*!
01800  * \internal
01801  * \brief Find or create an empty no-B-channel interface to use.
01802  * \since 1.8
01803  *
01804  * \param pri PRI span control structure.
01805  *
01806  * \note Assumes the pri->lock is already obtained.
01807  *
01808  * \retval array-index into private pointer array on success.
01809  * \retval -1 on error.
01810  */
01811 static int pri_find_empty_nobch(struct sig_pri_span *pri)
01812 {
01813    int idx;
01814 
01815    for (idx = 0; idx < pri->numchans; ++idx) {
01816       if (pri->pvts[idx]
01817          && pri->pvts[idx]->no_b_channel
01818          && sig_pri_is_chan_available(pri->pvts[idx])) {
01819          ast_debug(1, "Found empty available no B channel interface\n");
01820          return idx;
01821       }
01822    }
01823 
01824    /* Need to create a new interface. */
01825    if (pri->calls->new_nobch_intf) {
01826       idx = pri->calls->new_nobch_intf(pri);
01827    } else {
01828       idx = -1;
01829    }
01830    return idx;
01831 }
01832 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
01833 
01834 static void *do_idle_thread(void *v_pvt)
01835 {
01836    struct sig_pri_chan *pvt = v_pvt;
01837    struct ast_channel *chan = pvt->owner;
01838    struct ast_frame *f;
01839    char ex[80];
01840    /* Wait up to 30 seconds for an answer */
01841    int timeout_ms = 30000;
01842    int ms;
01843    struct timeval start;
01844 
01845    ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
01846    snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
01847    if (ast_call(chan, ex, 0)) {
01848       ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
01849       ast_hangup(chan);
01850       return NULL;
01851    }
01852    start = ast_tvnow();
01853    while ((ms = ast_remaining_ms(start, timeout_ms))) {
01854       if (ast_waitfor(chan, ms) <= 0) {
01855          break;
01856       }
01857 
01858       f = ast_read(chan);
01859       if (!f) {
01860          /* Got hangup */
01861          break;
01862       }
01863       if (f->frametype == AST_FRAME_CONTROL) {
01864          switch (f->subclass.integer) {
01865          case AST_CONTROL_ANSWER:
01866             /* Launch the PBX */
01867             ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
01868             ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
01869             chan->priority = 1;
01870             ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
01871             ast_pbx_run(chan);
01872             /* It's already hungup, return immediately */
01873             return NULL;
01874          case AST_CONTROL_BUSY:
01875             ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
01876             break;
01877          case AST_CONTROL_CONGESTION:
01878             ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
01879             break;
01880          };
01881       }
01882       ast_frfree(f);
01883    }
01884    /* Hangup the channel since nothing happend */
01885    ast_hangup(chan);
01886    return NULL;
01887 }
01888 
01889 static void *pri_ss_thread(void *data)
01890 {
01891    struct sig_pri_chan *p = data;
01892    struct ast_channel *chan = p->owner;
01893    char exten[AST_MAX_EXTENSION];
01894    int res;
01895    int len;
01896    int timeout;
01897 
01898    if (!chan) {
01899       /* We lost the owner before we could get started. */
01900       return NULL;
01901    }
01902 
01903    /*
01904     * In the bizarre case where the channel has become a zombie before we
01905     * even get started here, abort safely.
01906     */
01907    if (!chan->tech_pvt) {
01908       ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
01909       ast_hangup(chan);
01910       return NULL;
01911    }
01912 
01913    ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
01914 
01915    sig_pri_dsp_reset_and_flush_digits(p);
01916 
01917    /* Now loop looking for an extension */
01918    ast_copy_string(exten, p->exten, sizeof(exten));
01919    len = strlen(exten);
01920    res = 0;
01921    while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
01922       if (len && !ast_ignore_pattern(chan->context, exten))
01923          sig_pri_play_tone(p, -1);
01924       else
01925          sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
01926       if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
01927          timeout = pri_matchdigittimeout;
01928       else
01929          timeout = pri_gendigittimeout;
01930       res = ast_waitfordigit(chan, timeout);
01931       if (res < 0) {
01932          ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
01933          ast_hangup(chan);
01934          return NULL;
01935       } else if (res) {
01936          exten[len++] = res;
01937          exten[len] = '\0';
01938       } else
01939          break;
01940    }
01941    /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
01942    if (ast_strlen_zero(exten)) {
01943       ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
01944       exten[0] = 's';
01945       exten[1] = '\0';
01946    } else {
01947       ast_free(chan->dialed.number.str);
01948       chan->dialed.number.str = ast_strdup(exten);
01949 
01950       if (p->pri->append_msn_to_user_tag && p->pri->nodetype != PRI_NETWORK) {
01951          /*
01952           * Update the user tag for party id's from this device for this call
01953           * now that we have a complete MSN from the network.
01954           */
01955          snprintf(p->user_tag, sizeof(p->user_tag), "%s_%s", p->pri->initial_user_tag,
01956             exten);
01957          ast_free(chan->caller.id.tag);
01958          chan->caller.id.tag = ast_strdup(p->user_tag);
01959       }
01960    }
01961    sig_pri_play_tone(p, -1);
01962    if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
01963       /* Start the real PBX */
01964       ast_copy_string(chan->exten, exten, sizeof(chan->exten));
01965       sig_pri_dsp_reset_and_flush_digits(p);
01966 #if defined(JIRA_ASTERISK_15594)
01967       /*
01968        * Conditionaled out this code to effectively revert the JIRA
01969        * ASTERISK-15594 change.  It breaks overlap dialing through
01970        * Asterisk.  There is not enough information available at this
01971        * point to know if dialing is complete.  The
01972        * ast_exists_extension(), ast_matchmore_extension(), and
01973        * ast_canmatch_extension() calls are not adequate to detect a
01974        * dial through extension pattern of "_9!".
01975        *
01976        * Workaround is to use the dialplan Proceeding() application
01977        * early on non-dial through extensions.
01978        */
01979       if ((p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
01980          && !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
01981          sig_pri_lock_private(p);
01982          if (p->pri->pri) {
01983             pri_grab(p, p->pri);
01984             if (p->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING) {
01985                p->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
01986             }
01987             pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
01988             pri_rel(p->pri);
01989          }
01990          sig_pri_unlock_private(p);
01991       }
01992 #endif   /* defined(JIRA_ASTERISK_15594) */
01993 
01994       sig_pri_set_echocanceller(p, 1);
01995       ast_setstate(chan, AST_STATE_RING);
01996       res = ast_pbx_run(chan);
01997       if (res) {
01998          ast_log(LOG_WARNING, "PBX exited non-zero!\n");
01999       }
02000    } else {
02001       ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
02002       chan->hangupcause = AST_CAUSE_UNALLOCATED;
02003       ast_hangup(chan);
02004       p->exten[0] = '\0';
02005       /* Since we send release complete here, we won't get one */
02006       p->call = NULL;
02007       ast_mutex_lock(&p->pri->lock);
02008       sig_pri_span_devstate_changed(p->pri);
02009       ast_mutex_unlock(&p->pri->lock);
02010    }
02011    return NULL;
02012 }
02013 
02014 void pri_event_alarm(struct sig_pri_span *pri, int index, int before_start_pri)
02015 {
02016    pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
02017    if (!before_start_pri) {
02018       pri_find_dchan(pri);
02019    }
02020 }
02021 
02022 void pri_event_noalarm(struct sig_pri_span *pri, int index, int before_start_pri)
02023 {
02024    pri->dchanavail[index] |= DCHAN_NOTINALARM;
02025    if (!before_start_pri)
02026       pri_restart(pri->dchans[index]);
02027 }
02028 
02029 /*!
02030  * \internal
02031  * \brief Convert libpri party name into asterisk party name.
02032  * \since 1.8
02033  *
02034  * \param ast_name Asterisk party name structure to fill.  Must already be set initialized.
02035  * \param pri_name libpri party name structure containing source information.
02036  *
02037  * \note The filled in ast_name structure needs to be destroyed by
02038  * ast_party_name_free() when it is no longer needed.
02039  *
02040  * \return Nothing
02041  */
02042 static void sig_pri_party_name_convert(struct ast_party_name *ast_name, const struct pri_party_name *pri_name)
02043 {
02044    ast_name->str = ast_strdup(pri_name->str);
02045    ast_name->char_set = pri_to_ast_char_set(pri_name->char_set);
02046    ast_name->presentation = pri_to_ast_presentation(pri_name->presentation);
02047    ast_name->valid = 1;
02048 }
02049 
02050 /*!
02051  * \internal
02052  * \brief Convert libpri party number into asterisk party number.
02053  * \since 1.8
02054  *
02055  * \param ast_number Asterisk party number structure to fill.  Must already be set initialized.
02056  * \param pri_number libpri party number structure containing source information.
02057  * \param pri PRI span control structure.
02058  *
02059  * \note The filled in ast_number structure needs to be destroyed by
02060  * ast_party_number_free() when it is no longer needed.
02061  *
02062  * \return Nothing
02063  */
02064 static void sig_pri_party_number_convert(struct ast_party_number *ast_number, const struct pri_party_number *pri_number, struct sig_pri_span *pri)
02065 {
02066    char number[AST_MAX_EXTENSION];
02067 
02068    apply_plan_to_existing_number(number, sizeof(number), pri, pri_number->str,
02069       pri_number->plan);
02070    ast_number->str = ast_strdup(number);
02071    ast_number->plan = pri_number->plan;
02072    ast_number->presentation = pri_to_ast_presentation(pri_number->presentation);
02073    ast_number->valid = 1;
02074 }
02075 
02076 /*!
02077  * \internal
02078  * \brief Convert libpri party id into asterisk party id.
02079  * \since 1.8
02080  *
02081  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
02082  * \param pri_id libpri party id structure containing source information.
02083  * \param pri PRI span control structure.
02084  *
02085  * \note The filled in ast_id structure needs to be destroyed by
02086  * ast_party_id_free() when it is no longer needed.
02087  *
02088  * \return Nothing
02089  */
02090 static void sig_pri_party_id_convert(struct ast_party_id *ast_id, const struct pri_party_id *pri_id, struct sig_pri_span *pri)
02091 {
02092    if (pri_id->name.valid) {
02093       sig_pri_party_name_convert(&ast_id->name, &pri_id->name);
02094    }
02095    if (pri_id->number.valid) {
02096       sig_pri_party_number_convert(&ast_id->number, &pri_id->number, pri);
02097    }
02098 #if defined(HAVE_PRI_SUBADDR)
02099    if (pri_id->subaddress.valid) {
02100       sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
02101    }
02102 #endif   /* defined(HAVE_PRI_SUBADDR) */
02103 }
02104 
02105 /*!
02106  * \internal
02107  * \brief Convert libpri redirecting information into asterisk redirecting information.
02108  * \since 1.8
02109  *
02110  * \param ast_redirecting Asterisk redirecting structure to fill.
02111  * \param pri_redirecting libpri redirecting structure containing source information.
02112  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
02113  * \param pri PRI span control structure.
02114  *
02115  * \note The filled in ast_redirecting structure needs to be destroyed by
02116  * ast_party_redirecting_free() when it is no longer needed.
02117  *
02118  * \return Nothing
02119  */
02120 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
02121    const struct pri_party_redirecting *pri_redirecting,
02122    const struct ast_party_redirecting *ast_guide,
02123    struct sig_pri_span *pri)
02124 {
02125    ast_party_redirecting_set_init(ast_redirecting, ast_guide);
02126 
02127    sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
02128    sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
02129    ast_redirecting->count = pri_redirecting->count;
02130    ast_redirecting->reason = pri_to_ast_reason(pri_redirecting->reason);
02131 }
02132 
02133 /*!
02134  * \internal
02135  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
02136  * \since 1.8
02137  *
02138  * \param msn_patterns Comma separated list of MSN patterns to match.
02139  * \param exten Extension to match in the MSN list.
02140  *
02141  * \retval 1 if matches.
02142  * \retval 0 if no match.
02143  */
02144 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
02145 {
02146    char *pattern;
02147    char *msn_list;
02148    char *list_tail;
02149 
02150    msn_list = ast_strdupa(msn_patterns);
02151 
02152    list_tail = NULL;
02153    pattern = strtok_r(msn_list, ",", &list_tail);
02154    while (pattern) {
02155       pattern = ast_strip(pattern);
02156       if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
02157          /* Extension matched the pattern. */
02158          return 1;
02159       }
02160       pattern = strtok_r(NULL, ",", &list_tail);
02161    }
02162    /* Did not match any pattern in the list. */
02163    return 0;
02164 }
02165 
02166 #if defined(HAVE_PRI_MCID)
02167 /*!
02168  * \internal
02169  * \brief Append the given party id to the event string.
02170  * \since 1.8
02171  *
02172  * \param msg Event message string being built.
02173  * \param prefix Prefix to add to the party id lines.
02174  * \param party Party information to encode.
02175  *
02176  * \return Nothing
02177  */
02178 static void sig_pri_event_party_id(struct ast_str **msg, const char *prefix, struct ast_party_id *party)
02179 {
02180    int pres;
02181 
02182    /* Combined party presentation */
02183    pres = ast_party_id_presentation(party);
02184    ast_str_append(msg, 0, "%sPres: %d (%s)\r\n", prefix, pres,
02185       ast_describe_caller_presentation(pres));
02186 
02187    /* Party number */
02188    ast_str_append(msg, 0, "%sNumValid: %d\r\n", prefix,
02189       party->number.valid);
02190    ast_str_append(msg, 0, "%sNum: %s\r\n", prefix,
02191       S_COR(party->number.valid, party->number.str, ""));
02192    ast_str_append(msg, 0, "%ston: %d\r\n", prefix, party->number.plan);
02193    if (party->number.valid) {
02194       ast_str_append(msg, 0, "%sNumPlan: %d\r\n", prefix, party->number.plan);
02195       ast_str_append(msg, 0, "%sNumPres: %d (%s)\r\n", prefix,
02196          party->number.presentation,
02197          ast_describe_caller_presentation(party->number.presentation));
02198    }
02199 
02200    /* Party name */
02201    ast_str_append(msg, 0, "%sNameValid: %d\r\n", prefix,
02202       party->name.valid);
02203    ast_str_append(msg, 0, "%sName: %s\r\n", prefix,
02204       S_COR(party->name.valid, party->name.str, ""));
02205    if (party->name.valid) {
02206       ast_str_append(msg, 0, "%sNameCharSet: %s\r\n", prefix,
02207          ast_party_name_charset_describe(party->name.char_set));
02208       ast_str_append(msg, 0, "%sNamePres: %d (%s)\r\n", prefix,
02209          party->name.presentation,
02210          ast_describe_caller_presentation(party->name.presentation));
02211    }
02212 
02213 #if defined(HAVE_PRI_SUBADDR)
02214    /* Party subaddress */
02215    if (party->subaddress.valid) {
02216       static const char subaddress[] = "Subaddr";
02217 
02218       ast_str_append(msg, 0, "%s%s: %s\r\n", prefix, subaddress,
02219          S_OR(party->subaddress.str, ""));
02220       ast_str_append(msg, 0, "%s%sType: %d\r\n", prefix, subaddress,
02221          party->subaddress.type);
02222       ast_str_append(msg, 0, "%s%sOdd: %d\r\n", prefix, subaddress,
02223          party->subaddress.odd_even_indicator);
02224    }
02225 #endif   /* defined(HAVE_PRI_SUBADDR) */
02226 }
02227 #endif   /* defined(HAVE_PRI_MCID) */
02228 
02229 #if defined(HAVE_PRI_MCID)
02230 /*!
02231  * \internal
02232  * \brief Handle the MCID event.
02233  * \since 1.8
02234  *
02235  * \param pri PRI span control structure.
02236  * \param mcid MCID event parameters.
02237  * \param owner Asterisk channel associated with the call.
02238  * NULL if Asterisk no longer has the ast_channel struct.
02239  *
02240  * \note Assumes the pri->lock is already obtained.
02241  * \note Assumes the owner channel lock is already obtained if still present.
02242  *
02243  * \return Nothing
02244  */
02245 static void sig_pri_mcid_event(struct sig_pri_span *pri, const struct pri_subcmd_mcid_req *mcid, struct ast_channel *owner)
02246 {
02247    struct ast_channel *chans[1];
02248    struct ast_str *msg;
02249    struct ast_party_id party;
02250 
02251    msg = ast_str_create(4096);
02252    if (!msg) {
02253       return;
02254    }
02255 
02256    if (owner) {
02257       /* The owner channel is present. */
02258       ast_str_append(&msg, 0, "Channel: %s\r\n", owner->name);
02259       ast_str_append(&msg, 0, "UniqueID: %s\r\n", owner->uniqueid);
02260 
02261       sig_pri_event_party_id(&msg, "CallerID", &owner->connected.id);
02262    } else {
02263       /*
02264        * Since we no longer have an owner channel,
02265        * we have to use the caller information supplied by libpri.
02266        */
02267       ast_party_id_init(&party);
02268       sig_pri_party_id_convert(&party, &mcid->originator, pri);
02269       sig_pri_event_party_id(&msg, "CallerID", &party);
02270       ast_party_id_free(&party);
02271    }
02272 
02273    /* Always use libpri's called party information. */
02274    ast_party_id_init(&party);
02275    sig_pri_party_id_convert(&party, &mcid->answerer, pri);
02276    sig_pri_event_party_id(&msg, "ConnectedID", &party);
02277    ast_party_id_free(&party);
02278 
02279    chans[0] = owner;
02280    ast_manager_event_multichan(EVENT_FLAG_CALL, "MCID", owner ? 1 : 0, chans, "%s",
02281       ast_str_buffer(msg));
02282    ast_free(msg);
02283 }
02284 #endif   /* defined(HAVE_PRI_MCID) */
02285 
02286 #if defined(HAVE_PRI_TRANSFER)
02287 struct xfer_rsp_data {
02288    struct sig_pri_span *pri;
02289    /*! Call to send transfer success/fail response over. */
02290    q931_call *call;
02291    /*! Invocation ID to use when sending a reply to the transfer request. */
02292    int invoke_id;
02293 };
02294 #endif   /* defined(HAVE_PRI_TRANSFER) */
02295 
02296 #if defined(HAVE_PRI_TRANSFER)
02297 /*!
02298  * \internal
02299  * \brief Send the transfer success/fail response message.
02300  * \since 1.8
02301  *
02302  * \param data Callback user data pointer
02303  * \param is_successful TRUE if the transfer was successful.
02304  *
02305  * \return Nothing
02306  */
02307 static void sig_pri_transfer_rsp(void *data, int is_successful)
02308 {
02309    struct xfer_rsp_data *rsp = data;
02310 
02311    pri_transfer_rsp(rsp->pri->pri, rsp->call, rsp->invoke_id, is_successful);
02312 }
02313 #endif   /* defined(HAVE_PRI_TRANSFER) */
02314 
02315 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
02316 /*!
02317  * \brief Protocol callback to indicate if transfer will happen.
02318  * \since 1.8
02319  *
02320  * \param data Callback user data pointer
02321  * \param is_successful TRUE if the transfer will happen.
02322  *
02323  * \return Nothing
02324  */
02325 typedef void (*xfer_rsp_callback)(void *data, int is_successful);
02326 #endif   /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
02327 
02328 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
02329 /*!
02330  * \internal
02331  * \brief Attempt to transfer the two calls to each other.
02332  * \since 1.8
02333  *
02334  * \param pri PRI span control structure.
02335  * \param call_1_pri First call involved in the transfer. (transferee; usually on hold)
02336  * \param call_1_held TRUE if call_1_pri is on hold.
02337  * \param call_2_pri Second call involved in the transfer. (target; usually active/ringing)
02338  * \param call_2_held TRUE if call_2_pri is on hold.
02339  * \param rsp_callback Protocol callback to indicate if transfer will happen. NULL if not used.
02340  * \param data Callback user data pointer
02341  *
02342  * \note Assumes the pri->lock is already obtained.
02343  *
02344  * \retval 0 on success.
02345  * \retval -1 on error.
02346  */
02347 static int sig_pri_attempt_transfer(struct sig_pri_span *pri, q931_call *call_1_pri, int call_1_held, q931_call *call_2_pri, int call_2_held, xfer_rsp_callback rsp_callback, void *data)
02348 {
02349    struct attempt_xfer_call {
02350       q931_call *pri;
02351       struct ast_channel *ast;
02352       int held;
02353       int chanpos;
02354    };
02355    int retval;
02356    struct ast_channel *transferee;
02357    struct attempt_xfer_call *call_1;
02358    struct attempt_xfer_call *call_2;
02359    struct attempt_xfer_call *swap_call;
02360    struct attempt_xfer_call c1;
02361    struct attempt_xfer_call c2;
02362 
02363    c1.pri = call_1_pri;
02364    c1.held = call_1_held;
02365    call_1 = &c1;
02366 
02367    c2.pri = call_2_pri;
02368    c2.held = call_2_held;
02369    call_2 = &c2;
02370 
02371    call_1->chanpos = pri_find_principle_by_call(pri, call_1->pri);
02372    call_2->chanpos = pri_find_principle_by_call(pri, call_2->pri);
02373    if (call_1->chanpos < 0 || call_2->chanpos < 0) {
02374       /* Calls not found in span control. */
02375       if (rsp_callback) {
02376          /* Transfer failed. */
02377          rsp_callback(data, 0);
02378       }
02379       return -1;
02380    }
02381 
02382    /* Attempt to make transferee and target consistent. */
02383    if (!call_1->held && call_2->held) {
02384       /*
02385        * Swap call_1 and call_2 to make call_1 the transferee(held call)
02386        * and call_2 the target(active call).
02387        */
02388       swap_call = call_1;
02389       call_1 = call_2;
02390       call_2 = swap_call;
02391    }
02392 
02393    /* Deadlock avoidance is attempted. */
02394    sig_pri_lock_private(pri->pvts[call_1->chanpos]);
02395    sig_pri_lock_owner(pri, call_1->chanpos);
02396    sig_pri_lock_private(pri->pvts[call_2->chanpos]);
02397    sig_pri_lock_owner(pri, call_2->chanpos);
02398 
02399    call_1->ast = pri->pvts[call_1->chanpos]->owner;
02400    call_2->ast = pri->pvts[call_2->chanpos]->owner;
02401    if (!call_1->ast || !call_2->ast) {
02402       /* At least one owner is not present. */
02403       if (call_1->ast) {
02404          ast_channel_unlock(call_1->ast);
02405       }
02406       if (call_2->ast) {
02407          ast_channel_unlock(call_2->ast);
02408       }
02409       sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
02410       sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
02411       if (rsp_callback) {
02412          /* Transfer failed. */
02413          rsp_callback(data, 0);
02414       }
02415       return -1;
02416    }
02417 
02418    for (;;) {
02419       transferee = ast_bridged_channel(call_1->ast);
02420       if (transferee) {
02421          break;
02422       }
02423 
02424       /* Try masquerading the other way. */
02425       swap_call = call_1;
02426       call_1 = call_2;
02427       call_2 = swap_call;
02428 
02429       transferee = ast_bridged_channel(call_1->ast);
02430       if (transferee) {
02431          break;
02432       }
02433 
02434       /* Could not transfer.  Neither call is bridged. */
02435       ast_channel_unlock(call_1->ast);
02436       ast_channel_unlock(call_2->ast);
02437       sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
02438       sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
02439 
02440       if (rsp_callback) {
02441          /* Transfer failed. */
02442          rsp_callback(data, 0);
02443       }
02444       return -1;
02445    }
02446 
02447    ast_verb(3, "TRANSFERRING %s to %s\n", call_1->ast->name, call_2->ast->name);
02448 
02449    /*
02450     * Setup transfer masquerade.
02451     *
02452     * Note:  There is an extremely nasty deadlock avoidance issue
02453     * with ast_channel_transfer_masquerade().  Deadlock may be possible if
02454     * the channels involved are proxies (chan_agent channels) and
02455     * it is called with locks.  Unfortunately, there is no simple
02456     * or even merely difficult way to guarantee deadlock avoidance
02457     * and still be able to send an ECT success response without the
02458     * possibility of the bridged channel hanging up on us.
02459     */
02460    ast_mutex_unlock(&pri->lock);
02461    retval = ast_channel_transfer_masquerade(
02462       call_2->ast,
02463       &call_2->ast->connected,
02464       call_2->held,
02465       transferee,
02466       &call_1->ast->connected,
02467       call_1->held);
02468 
02469    /* Reacquire the pri->lock to hold off completion of the transfer masquerade. */
02470    ast_mutex_lock(&pri->lock);
02471 
02472    ast_channel_unlock(call_1->ast);
02473    ast_channel_unlock(call_2->ast);
02474    sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
02475    sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
02476 
02477    if (rsp_callback) {
02478       /*
02479        * Report transfer status.
02480        *
02481        * Must do the callback before the masquerade completes to ensure
02482        * that the protocol message goes out before the call leg is
02483        * disconnected.
02484        */
02485       rsp_callback(data, retval ? 0 : 1);
02486    }
02487    return retval;
02488 }
02489 #endif   /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
02490 
02491 #if defined(HAVE_PRI_CCSS)
02492 /*!
02493  * \internal
02494  * \brief Compare the CC agent private data by libpri cc_id.
02495  * \since 1.8
02496  *
02497  * \param obj pointer to the (user-defined part) of an object.
02498  * \param arg callback argument from ao2_callback()
02499  * \param flags flags from ao2_callback()
02500  *
02501  * \return values are a combination of enum _cb_results.
02502  */
02503 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
02504 {
02505    struct ast_cc_agent *agent_1 = obj;
02506    struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
02507    struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
02508 
02509    return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
02510       && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
02511 }
02512 #endif   /* defined(HAVE_PRI_CCSS) */
02513 
02514 #if defined(HAVE_PRI_CCSS)
02515 /*!
02516  * \internal
02517  * \brief Find the CC agent by libpri cc_id.
02518  * \since 1.8
02519  *
02520  * \param pri PRI span control structure.
02521  * \param cc_id CC record ID to find.
02522  *
02523  * \note
02524  * Since agents are refcounted, and this function returns
02525  * a reference to the agent, it is imperative that you decrement
02526  * the refcount of the agent once you have finished using it.
02527  *
02528  * \retval agent on success.
02529  * \retval NULL not found.
02530  */
02531 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_span *pri, long cc_id)
02532 {
02533    struct sig_pri_cc_agent_prv finder = {
02534       .pri = pri,
02535       .cc_id = cc_id,
02536    };
02537 
02538    return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
02539       sig_pri_cc_type_name);
02540 }
02541 #endif   /* defined(HAVE_PRI_CCSS) */
02542 
02543 #if defined(HAVE_PRI_CCSS)
02544 /*!
02545  * \internal
02546  * \brief Compare the CC monitor instance by libpri cc_id.
02547  * \since 1.8
02548  *
02549  * \param obj pointer to the (user-defined part) of an object.
02550  * \param arg callback argument from ao2_callback()
02551  * \param flags flags from ao2_callback()
02552  *
02553  * \return values are a combination of enum _cb_results.
02554  */
02555 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
02556 {
02557    struct sig_pri_cc_monitor_instance *monitor_1 = obj;
02558    struct sig_pri_cc_monitor_instance *monitor_2 = arg;
02559 
02560    return (monitor_1->pri == monitor_2->pri
02561       && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
02562 }
02563 #endif   /* defined(HAVE_PRI_CCSS) */
02564 
02565 #if defined(HAVE_PRI_CCSS)
02566 /*!
02567  * \internal
02568  * \brief Find the CC monitor instance by libpri cc_id.
02569  * \since 1.8
02570  *
02571  * \param pri PRI span control structure.
02572  * \param cc_id CC record ID to find.
02573  *
02574  * \note
02575  * Since monitor_instances are refcounted, and this function returns
02576  * a reference to the instance, it is imperative that you decrement
02577  * the refcount of the instance once you have finished using it.
02578  *
02579  * \retval monitor_instance on success.
02580  * \retval NULL not found.
02581  */
02582 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_span *pri, long cc_id)
02583 {
02584    struct sig_pri_cc_monitor_instance finder = {
02585       .pri = pri,
02586       .cc_id = cc_id,
02587    };
02588 
02589    return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
02590 }
02591 #endif   /* defined(HAVE_PRI_CCSS) */
02592 
02593 #if defined(HAVE_PRI_CCSS)
02594 /*!
02595  * \internal
02596  * \brief Destroy the given monitor instance.
02597  * \since 1.8
02598  *
02599  * \param data Monitor instance to destroy.
02600  *
02601  * \return Nothing
02602  */
02603 static void sig_pri_cc_monitor_instance_destroy(void *data)
02604 {
02605    struct sig_pri_cc_monitor_instance *monitor_instance = data;
02606 
02607    if (monitor_instance->cc_id != -1) {
02608       ast_mutex_lock(&monitor_instance->pri->lock);
02609       pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
02610       ast_mutex_unlock(&monitor_instance->pri->lock);
02611    }
02612    monitor_instance->pri->calls->module_unref();
02613 }
02614 #endif   /* defined(HAVE_PRI_CCSS) */
02615 
02616 #if defined(HAVE_PRI_CCSS)
02617 /*!
02618  * \internal
02619  * \brief Construct a new monitor instance.
02620  * \since 1.8
02621  *
02622  * \param core_id CC core ID.
02623  * \param pri PRI span control structure.
02624  * \param cc_id CC record ID.
02625  * \param device_name Name of device (Asterisk channel name less sequence number).
02626  *
02627  * \note
02628  * Since monitor_instances are refcounted, and this function returns
02629  * a reference to the instance, it is imperative that you decrement
02630  * the refcount of the instance once you have finished using it.
02631  *
02632  * \retval monitor_instance on success.
02633  * \retval NULL on error.
02634  */
02635 static struct sig_pri_cc_monitor_instance *sig_pri_cc_monitor_instance_init(int core_id, struct sig_pri_span *pri, long cc_id, const char *device_name)
02636 {
02637    struct sig_pri_cc_monitor_instance *monitor_instance;
02638 
02639    if (!pri->calls->module_ref || !pri->calls->module_unref) {
02640       return NULL;
02641    }
02642 
02643    monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
02644       sig_pri_cc_monitor_instance_destroy);
02645    if (!monitor_instance) {
02646       return NULL;
02647    }
02648 
02649    monitor_instance->cc_id = cc_id;
02650    monitor_instance->pri = pri;
02651    monitor_instance->core_id = core_id;
02652    strcpy(monitor_instance->name, device_name);
02653 
02654    pri->calls->module_ref();
02655 
02656    ao2_link(sig_pri_cc_monitors, monitor_instance);
02657    return monitor_instance;
02658 }
02659 #endif   /* defined(HAVE_PRI_CCSS) */
02660 
02661 #if defined(HAVE_PRI_CCSS)
02662 /*!
02663  * \internal
02664  * \brief Announce to the CC core that protocol CC monitor is available for this call.
02665  * \since 1.8
02666  *
02667  * \param pri PRI span control structure.
02668  * \param chanpos Channel position in the span.
02669  * \param cc_id CC record ID.
02670  * \param service CCBS/CCNR indication.
02671  *
02672  * \note Assumes the pri->lock is already obtained.
02673  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
02674  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
02675  *
02676  * \retval 0 on success.
02677  * \retval -1 on error.
02678  */
02679 static int sig_pri_cc_available(struct sig_pri_span *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
02680 {
02681    struct sig_pri_chan *pvt;
02682    struct ast_cc_config_params *cc_params;
02683    struct sig_pri_cc_monitor_instance *monitor;
02684    enum ast_cc_monitor_policies monitor_policy;
02685    int core_id;
02686    int res;
02687    char device_name[AST_CHANNEL_NAME];
02688    char dialstring[AST_CHANNEL_NAME];
02689 
02690    pvt = pri->pvts[chanpos];
02691 
02692    core_id = ast_cc_get_current_core_id(pvt->owner);
02693    if (core_id == -1) {
02694       return -1;
02695    }
02696 
02697    cc_params = ast_channel_get_cc_config_params(pvt->owner);
02698    if (!cc_params) {
02699       return -1;
02700    }
02701 
02702    res = -1;
02703    monitor_policy = ast_get_cc_monitor_policy(cc_params);
02704    switch (monitor_policy) {
02705    case AST_CC_MONITOR_NEVER:
02706       /* CCSS is not enabled. */
02707       break;
02708    case AST_CC_MONITOR_NATIVE:
02709    case AST_CC_MONITOR_ALWAYS:
02710       /*
02711        * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
02712        * later in the call to sig_pri_cc_generic_check().
02713        */
02714       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02715       sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
02716       monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
02717       if (!monitor) {
02718          break;
02719       }
02720       res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
02721          monitor);
02722       if (res) {
02723          monitor->cc_id = -1;
02724          ao2_unlink(sig_pri_cc_monitors, monitor);
02725          ao2_ref(monitor, -1);
02726       }
02727       break;
02728    case AST_CC_MONITOR_GENERIC:
02729       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
02730          sig_pri_get_orig_dialstring(pvt), service, NULL);
02731       /* Say it failed to force caller to cancel native CC. */
02732       break;
02733    }
02734    return res;
02735 }
02736 #endif   /* defined(HAVE_PRI_CCSS) */
02737 
02738 /*!
02739  * \internal
02740  * \brief Check if generic CC monitor is needed and request it.
02741  * \since 1.8
02742  *
02743  * \param pri PRI span control structure.
02744  * \param chanpos Channel position in the span.
02745  * \param service CCBS/CCNR indication.
02746  *
02747  * \note Assumes the pri->lock is already obtained.
02748  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
02749  *
02750  * \return Nothing
02751  */
02752 static void sig_pri_cc_generic_check(struct sig_pri_span *pri, int chanpos, enum ast_cc_service_type service)
02753 {
02754    struct ast_channel *owner;
02755    struct ast_cc_config_params *cc_params;
02756 #if defined(HAVE_PRI_CCSS)
02757    struct ast_cc_monitor *monitor;
02758    char device_name[AST_CHANNEL_NAME];
02759 #endif   /* defined(HAVE_PRI_CCSS) */
02760    enum ast_cc_monitor_policies monitor_policy;
02761    int core_id;
02762 
02763    if (!pri->pvts[chanpos]->outgoing) {
02764       /* This is not an outgoing call so it cannot be CC monitor. */
02765       return;
02766    }
02767 
02768    sig_pri_lock_owner(pri, chanpos);
02769    owner = pri->pvts[chanpos]->owner;
02770    if (!owner) {
02771       return;
02772    }
02773    core_id = ast_cc_get_current_core_id(owner);
02774    if (core_id == -1) {
02775       /* No CC core setup */
02776       goto done;
02777    }
02778 
02779    cc_params = ast_channel_get_cc_config_params(owner);
02780    if (!cc_params) {
02781       /* Could not get CC config parameters. */
02782       goto done;
02783    }
02784 
02785 #if defined(HAVE_PRI_CCSS)
02786    ast_channel_get_device_name(owner, device_name, sizeof(device_name));
02787    monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
02788    if (monitor) {
02789       /* CC monitor is already present so no need for generic CC. */
02790       ao2_ref(monitor, -1);
02791       goto done;
02792    }
02793 #endif   /* defined(HAVE_PRI_CCSS) */
02794 
02795    monitor_policy = ast_get_cc_monitor_policy(cc_params);
02796    switch (monitor_policy) {
02797    case AST_CC_MONITOR_NEVER:
02798       /* CCSS is not enabled. */
02799       break;
02800    case AST_CC_MONITOR_NATIVE:
02801       if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
02802          /* Request generic CC monitor. */
02803          ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
02804             sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
02805       }
02806       break;
02807    case AST_CC_MONITOR_ALWAYS:
02808       if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
02809          /*
02810           * Cannot monitor PTMP TE side since this is not defined.
02811           * We are playing the roll of a phone in this case and
02812           * a phone cannot monitor a party over the network without
02813           * protocol help.
02814           */
02815          break;
02816       }
02817       /*
02818        * We are either falling back or this is a PTMP NT span.
02819        * Request generic CC monitor.
02820        */
02821       ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
02822          sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
02823       break;
02824    case AST_CC_MONITOR_GENERIC:
02825       if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
02826          /* Request generic CC monitor. */
02827          ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
02828             sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
02829       }
02830       break;
02831    }
02832 
02833 done:
02834    ast_channel_unlock(owner);
02835 }
02836 
02837 #if defined(HAVE_PRI_CCSS)
02838 /*!
02839  * \internal
02840  * \brief The CC link canceled the CC instance.
02841  * \since 1.8
02842  *
02843  * \param pri PRI span control structure.
02844  * \param cc_id CC record ID.
02845  * \param is_agent TRUE if the cc_id is for an agent.
02846  *
02847  * \return Nothing
02848  */
02849 static void sig_pri_cc_link_canceled(struct sig_pri_span *pri, long cc_id, int is_agent)
02850 {
02851    if (is_agent) {
02852       struct ast_cc_agent *agent;
02853 
02854       agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
02855       if (!agent) {
02856          return;
02857       }
02858       ast_cc_failed(agent->core_id, "%s agent got canceled by link",
02859          sig_pri_cc_type_name);
02860       ao2_ref(agent, -1);
02861    } else {
02862       struct sig_pri_cc_monitor_instance *monitor;
02863 
02864       monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
02865       if (!monitor) {
02866          return;
02867       }
02868       monitor->cc_id = -1;
02869       ast_cc_monitor_failed(monitor->core_id, monitor->name,
02870          "%s monitor got canceled by link", sig_pri_cc_type_name);
02871       ao2_ref(monitor, -1);
02872    }
02873 }
02874 #endif   /* defined(HAVE_PRI_CCSS) */
02875 
02876 #if defined(HAVE_PRI_AOC_EVENTS)
02877 /*!
02878  * \internal
02879  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
02880  * \since 1.8
02881  *
02882  * \param value Value to convert to string.
02883  *
02884  * \return PRI_AOC_CHARGED_ITEM
02885  */
02886 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
02887 {
02888    switch (value) {
02889    case AST_AOC_CHARGED_ITEM_NA:
02890       return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
02891    case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
02892       return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
02893    case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
02894       return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
02895    case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
02896       return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
02897    case AST_AOC_CHARGED_ITEM_CALL_SETUP:
02898       return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
02899    case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
02900       return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
02901    case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
02902       return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
02903    }
02904    return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
02905 }
02906 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
02907 
02908 #if defined(HAVE_PRI_AOC_EVENTS)
02909 /*!
02910  * \internal
02911  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
02912  * \since 1.8
02913  *
02914  * \param value Value to convert to string.
02915  *
02916  * \return ast_aoc_charged_item
02917  */
02918 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
02919 {
02920    switch (value) {
02921    case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
02922       return AST_AOC_CHARGED_ITEM_NA;
02923    case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
02924       return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
02925    case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
02926       return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
02927    case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
02928       return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
02929    case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
02930       return AST_AOC_CHARGED_ITEM_CALL_SETUP;
02931    case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
02932       return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
02933    case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
02934       return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
02935    }
02936    return AST_AOC_CHARGED_ITEM_NA;
02937 }
02938 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
02939 
02940 #if defined(HAVE_PRI_AOC_EVENTS)
02941 /*!
02942  * \internal
02943  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
02944  * \since 1.8
02945  *
02946  * \return pri enum equivalent.
02947  */
02948 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
02949 {
02950    switch (mult) {
02951    case AST_AOC_MULT_ONETHOUSANDTH:
02952       return PRI_AOC_MULTIPLIER_THOUSANDTH;
02953    case AST_AOC_MULT_ONEHUNDREDTH:
02954       return PRI_AOC_MULTIPLIER_HUNDREDTH;
02955    case AST_AOC_MULT_ONETENTH:
02956       return PRI_AOC_MULTIPLIER_TENTH;
02957    case AST_AOC_MULT_ONE:
02958       return PRI_AOC_MULTIPLIER_ONE;
02959    case AST_AOC_MULT_TEN:
02960       return PRI_AOC_MULTIPLIER_TEN;
02961    case AST_AOC_MULT_HUNDRED:
02962       return PRI_AOC_MULTIPLIER_HUNDRED;
02963    case AST_AOC_MULT_THOUSAND:
02964       return PRI_AOC_MULTIPLIER_THOUSAND;
02965    default:
02966       return PRI_AOC_MULTIPLIER_ONE;
02967    }
02968 }
02969 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
02970 
02971 #if defined(HAVE_PRI_AOC_EVENTS)
02972 /*!
02973  * \internal
02974  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
02975  * \since 1.8
02976  *
02977  * \return ast enum equivalent.
02978  */
02979 static int sig_pri_aoc_multiplier_from_pri(const int mult)
02980 {
02981    switch (mult) {
02982    case PRI_AOC_MULTIPLIER_THOUSANDTH:
02983       return AST_AOC_MULT_ONETHOUSANDTH;
02984    case PRI_AOC_MULTIPLIER_HUNDREDTH:
02985       return AST_AOC_MULT_ONEHUNDREDTH;
02986    case PRI_AOC_MULTIPLIER_TENTH:
02987       return AST_AOC_MULT_ONETENTH;
02988    case PRI_AOC_MULTIPLIER_ONE:
02989       return AST_AOC_MULT_ONE;
02990    case PRI_AOC_MULTIPLIER_TEN:
02991       return AST_AOC_MULT_TEN;
02992    case PRI_AOC_MULTIPLIER_HUNDRED:
02993       return AST_AOC_MULT_HUNDRED;
02994    case PRI_AOC_MULTIPLIER_THOUSAND:
02995       return AST_AOC_MULT_THOUSAND;
02996    default:
02997       return AST_AOC_MULT_ONE;
02998    }
02999 }
03000 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03001 
03002 #if defined(HAVE_PRI_AOC_EVENTS)
03003 /*!
03004  * \internal
03005  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
03006  * \since 1.8
03007  *
03008  * \param value Value to convert to ast representation
03009  *
03010  * \return PRI_AOC_TIME_SCALE
03011  */
03012 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
03013 {
03014    switch (value) {
03015    default:
03016    case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
03017       return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
03018    case AST_AOC_TIME_SCALE_TENTH_SECOND:
03019       return PRI_AOC_TIME_SCALE_TENTH_SECOND;
03020    case AST_AOC_TIME_SCALE_SECOND:
03021       return PRI_AOC_TIME_SCALE_SECOND;
03022    case AST_AOC_TIME_SCALE_TEN_SECOND:
03023       return PRI_AOC_TIME_SCALE_TEN_SECOND;
03024    case AST_AOC_TIME_SCALE_MINUTE:
03025       return PRI_AOC_TIME_SCALE_MINUTE;
03026    case AST_AOC_TIME_SCALE_HOUR:
03027       return PRI_AOC_TIME_SCALE_HOUR;
03028    case AST_AOC_TIME_SCALE_DAY:
03029       return PRI_AOC_TIME_SCALE_DAY;
03030    }
03031 }
03032 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03033 
03034 #if defined(HAVE_PRI_AOC_EVENTS)
03035 /*!
03036  * \internal
03037  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
03038  * \since 1.8
03039  *
03040  * \param value Value to convert to ast representation
03041  *
03042  * \return ast aoc time scale
03043  */
03044 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
03045 {
03046    switch (value) {
03047    default:
03048    case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
03049       return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
03050    case PRI_AOC_TIME_SCALE_TENTH_SECOND:
03051       return AST_AOC_TIME_SCALE_TENTH_SECOND;
03052    case PRI_AOC_TIME_SCALE_SECOND:
03053       return AST_AOC_TIME_SCALE_SECOND;
03054    case PRI_AOC_TIME_SCALE_TEN_SECOND:
03055       return AST_AOC_TIME_SCALE_TEN_SECOND;
03056    case PRI_AOC_TIME_SCALE_MINUTE:
03057       return AST_AOC_TIME_SCALE_MINUTE;
03058    case PRI_AOC_TIME_SCALE_HOUR:
03059       return AST_AOC_TIME_SCALE_HOUR;
03060    case PRI_AOC_TIME_SCALE_DAY:
03061       return AST_AOC_TIME_SCALE_DAY;
03062    }
03063    return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
03064 }
03065 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03066 
03067 #if defined(HAVE_PRI_AOC_EVENTS)
03068 /*!
03069  * \internal
03070  * \brief Handle AOC-S control frame
03071  * \since 1.8
03072  *
03073  * \param aoc_s AOC-S event parameters.
03074  * \param owner Asterisk channel associated with the call.
03075  * \param passthrough indicating if this message should be queued on the ast channel
03076  *
03077  * \note Assumes the pri->lock is already obtained.
03078  * \note Assumes the sig_pri private is locked
03079  * \note Assumes the owner channel lock is already obtained.
03080  *
03081  * \return Nothing
03082  */
03083 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
03084 {
03085    struct ast_aoc_decoded *decoded = NULL;
03086    struct ast_aoc_encoded *encoded = NULL;
03087    size_t encoded_size = 0;
03088    int idx;
03089 
03090    if (!owner || !aoc_s) {
03091       return;
03092    }
03093 
03094    if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
03095       return;
03096    }
03097 
03098    for (idx = 0; idx < aoc_s->num_items; ++idx) {
03099       enum ast_aoc_s_charged_item charged_item;
03100 
03101       charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
03102       if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
03103          /* Delete the unknown charged item from the list. */
03104          continue;
03105       }
03106       switch (aoc_s->item[idx].rate_type) {
03107       case PRI_AOC_RATE_TYPE_DURATION:
03108          ast_aoc_s_add_rate_duration(decoded,
03109             charged_item,
03110             aoc_s->item[idx].rate.duration.amount.cost,
03111             sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
03112             aoc_s->item[idx].rate.duration.currency,
03113             aoc_s->item[idx].rate.duration.time.length,
03114             sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
03115             aoc_s->item[idx].rate.duration.granularity.length,
03116             sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
03117             aoc_s->item[idx].rate.duration.charging_type);
03118          break;
03119       case PRI_AOC_RATE_TYPE_FLAT:
03120          ast_aoc_s_add_rate_flat(decoded,
03121             charged_item,
03122             aoc_s->item[idx].rate.flat.amount.cost,
03123             sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
03124             aoc_s->item[idx].rate.flat.currency);
03125          break;
03126       case PRI_AOC_RATE_TYPE_VOLUME:
03127          ast_aoc_s_add_rate_volume(decoded,
03128             charged_item,
03129             aoc_s->item[idx].rate.volume.unit,
03130             aoc_s->item[idx].rate.volume.amount.cost,
03131             sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
03132             aoc_s->item[idx].rate.volume.currency);
03133          break;
03134       case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
03135          ast_aoc_s_add_rate_special_charge_code(decoded,
03136             charged_item,
03137             aoc_s->item[idx].rate.special);
03138          break;
03139       case PRI_AOC_RATE_TYPE_FREE:
03140          ast_aoc_s_add_rate_free(decoded, charged_item, 0);
03141          break;
03142       case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
03143          ast_aoc_s_add_rate_free(decoded, charged_item, 1);
03144          break;
03145       default:
03146          ast_aoc_s_add_rate_na(decoded, charged_item);
03147          break;
03148       }
03149    }
03150 
03151    if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
03152       ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
03153    }
03154 
03155    ast_aoc_manager_event(decoded, owner);
03156 
03157    ast_aoc_destroy_decoded(decoded);
03158    ast_aoc_destroy_encoded(encoded);
03159 }
03160 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03161 
03162 #if defined(HAVE_PRI_AOC_EVENTS)
03163 /*!
03164  * \internal
03165  * \brief Generate AOC Request Response
03166  * \since 1.8
03167  *
03168  * \param aoc_request
03169  *
03170  * \note Assumes the pri->lock is already obtained.
03171  * \note Assumes the sig_pri private is locked
03172  * \note Assumes the owner channel lock is already obtained.
03173  *
03174  * \return Nothing
03175  */
03176 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
03177 {
03178    int request;
03179 
03180    if (!aoc_request) {
03181       return;
03182    }
03183 
03184    request = aoc_request->charging_request;
03185 
03186    if (request & PRI_AOC_REQUEST_S) {
03187       if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
03188          /* An AOC-S response must come from the other side, so save off this invoke_id
03189           * and see if an AOC-S message comes in before the call is answered. */
03190          pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
03191          pvt->aoc_s_request_invoke_id_valid = 1;
03192 
03193       } else {
03194          pri_aoc_s_request_response_send(pvt->pri->pri,
03195             call,
03196             aoc_request->invoke_id,
03197             NULL);
03198       }
03199    }
03200 
03201    if (request & PRI_AOC_REQUEST_D) {
03202       if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
03203          pri_aoc_de_request_response_send(pvt->pri->pri,
03204             call,
03205             PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
03206             aoc_request->invoke_id);
03207       } else {
03208          pri_aoc_de_request_response_send(pvt->pri->pri,
03209             call,
03210             PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
03211             aoc_request->invoke_id);
03212       }
03213    }
03214 
03215    if (request & PRI_AOC_REQUEST_E) {
03216       if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
03217          pri_aoc_de_request_response_send(pvt->pri->pri,
03218             call,
03219             PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
03220             aoc_request->invoke_id);
03221       } else {
03222          pri_aoc_de_request_response_send(pvt->pri->pri,
03223             call,
03224             PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
03225             aoc_request->invoke_id);
03226       }
03227    }
03228 }
03229 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03230 
03231 #if defined(HAVE_PRI_AOC_EVENTS)
03232 /*!
03233  * \internal
03234  * \brief Generate AOC-D AST_CONTROL_AOC frame
03235  * \since 1.8
03236  *
03237  * \param aoc_e AOC-D event parameters.
03238  * \param owner Asterisk channel associated with the call.
03239  * \param passthrough indicating if this message should be queued on the ast channel
03240  *
03241  * \note Assumes the pri->lock is already obtained.
03242  * \note Assumes the sig_pri private is locked
03243  * \note Assumes the owner channel lock is already obtained.
03244  *
03245  * \return Nothing
03246  */
03247 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
03248 {
03249    struct ast_aoc_decoded *decoded = NULL;
03250    struct ast_aoc_encoded *encoded = NULL;
03251    size_t encoded_size = 0;
03252    enum ast_aoc_charge_type type;
03253 
03254    if (!owner || !aoc_d) {
03255       return;
03256    }
03257 
03258    switch (aoc_d->charge) {
03259    case PRI_AOC_DE_CHARGE_CURRENCY:
03260       type = AST_AOC_CHARGE_CURRENCY;
03261       break;
03262    case PRI_AOC_DE_CHARGE_UNITS:
03263       type = AST_AOC_CHARGE_UNIT;
03264       break;
03265    case PRI_AOC_DE_CHARGE_FREE:
03266       type = AST_AOC_CHARGE_FREE;
03267       break;
03268    default:
03269       type = AST_AOC_CHARGE_NA;
03270       break;
03271    }
03272 
03273    if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
03274       return;
03275    }
03276 
03277    switch (aoc_d->billing_accumulation) {
03278    default:
03279       ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
03280          aoc_d->billing_accumulation);
03281       /* Fall through */
03282    case 0:/* subTotal */
03283       ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
03284       break;
03285    case 1:/* total */
03286       ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
03287       break;
03288    }
03289 
03290    switch (aoc_d->billing_id) {
03291    case PRI_AOC_D_BILLING_ID_NORMAL:
03292       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
03293       break;
03294    case PRI_AOC_D_BILLING_ID_REVERSE:
03295       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
03296       break;
03297    case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
03298       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
03299       break;
03300    case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
03301    default:
03302       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
03303       break;
03304    }
03305 
03306    switch (aoc_d->charge) {
03307    case PRI_AOC_DE_CHARGE_CURRENCY:
03308       ast_aoc_set_currency_info(decoded,
03309          aoc_d->recorded.money.amount.cost,
03310          sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
03311          aoc_d->recorded.money.currency);
03312       break;
03313    case PRI_AOC_DE_CHARGE_UNITS:
03314       {
03315          int i;
03316          for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
03317             /* if type or number are negative, then they are not present */
03318             ast_aoc_add_unit_entry(decoded,
03319                (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
03320                aoc_d->recorded.unit.item[i].number,
03321                (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
03322                aoc_d->recorded.unit.item[i].type);
03323          }
03324       }
03325       break;
03326    }
03327 
03328    if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
03329       ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
03330    }
03331 
03332    ast_aoc_manager_event(decoded, owner);
03333 
03334    ast_aoc_destroy_decoded(decoded);
03335    ast_aoc_destroy_encoded(encoded);
03336 }
03337 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03338 
03339 #if defined(HAVE_PRI_AOC_EVENTS)
03340 /*!
03341  * \internal
03342  * \brief Generate AOC-E AST_CONTROL_AOC frame
03343  * \since 1.8
03344  *
03345  * \param aoc_e AOC-E event parameters.
03346  * \param owner Asterisk channel associated with the call.
03347  * \param passthrough indicating if this message should be queued on the ast channel
03348  *
03349  * \note Assumes the pri->lock is already obtained.
03350  * \note Assumes the sig_pri private is locked
03351  * \note Assumes the owner channel lock is already obtained.
03352  * \note owner channel may be NULL. In that case, generate event only
03353  *
03354  * \return Nothing
03355  */
03356 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
03357 {
03358    struct ast_aoc_decoded *decoded = NULL;
03359    struct ast_aoc_encoded *encoded = NULL;
03360    size_t encoded_size = 0;
03361    enum ast_aoc_charge_type type;
03362 
03363    if (!aoc_e) {
03364       return;
03365    }
03366 
03367    switch (aoc_e->charge) {
03368    case PRI_AOC_DE_CHARGE_CURRENCY:
03369       type = AST_AOC_CHARGE_CURRENCY;
03370       break;
03371    case PRI_AOC_DE_CHARGE_UNITS:
03372       type = AST_AOC_CHARGE_UNIT;
03373       break;
03374    case PRI_AOC_DE_CHARGE_FREE:
03375       type = AST_AOC_CHARGE_FREE;
03376       break;
03377    default:
03378       type = AST_AOC_CHARGE_NA;
03379       break;
03380    }
03381 
03382    if (!(decoded = ast_aoc_create(AST_AOC_E, type, 0))) {
03383       return;
03384    }
03385 
03386    switch (aoc_e->associated.charging_type) {
03387    case PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER:
03388       if (!aoc_e->associated.charge.number.valid) {
03389          break;
03390       }
03391       ast_aoc_set_association_number(decoded, aoc_e->associated.charge.number.str, aoc_e->associated.charge.number.plan);
03392       break;
03393    case PRI_AOC_E_CHARGING_ASSOCIATION_ID:
03394       ast_aoc_set_association_id(decoded, aoc_e->associated.charge.id);
03395       break;
03396    default:
03397       break;
03398    }
03399 
03400    switch (aoc_e->billing_id) {
03401    case PRI_AOC_E_BILLING_ID_NORMAL:
03402       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
03403       break;
03404    case PRI_AOC_E_BILLING_ID_REVERSE:
03405       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
03406       break;
03407    case PRI_AOC_E_BILLING_ID_CREDIT_CARD:
03408       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
03409       break;
03410    case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL:
03411       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL);
03412       break;
03413    case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY:
03414       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_BUSY);
03415       break;
03416    case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY:
03417       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_NO_REPLY);
03418       break;
03419    case PRI_AOC_E_BILLING_ID_CALL_DEFLECTION:
03420       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_DEFLECTION);
03421       break;
03422    case PRI_AOC_E_BILLING_ID_CALL_TRANSFER:
03423       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_TRANSFER);
03424       break;
03425    case PRI_AOC_E_BILLING_ID_NOT_AVAILABLE:
03426    default:
03427       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
03428       break;
03429    }
03430 
03431    switch (aoc_e->charge) {
03432    case PRI_AOC_DE_CHARGE_CURRENCY:
03433       ast_aoc_set_currency_info(decoded,
03434          aoc_e->recorded.money.amount.cost,
03435          sig_pri_aoc_multiplier_from_pri(aoc_e->recorded.money.amount.multiplier),
03436          aoc_e->recorded.money.currency);
03437       break;
03438    case PRI_AOC_DE_CHARGE_UNITS:
03439       {
03440          int i;
03441          for (i = 0; i < aoc_e->recorded.unit.num_items; ++i) {
03442             /* if type or number are negative, then they are not present */
03443             ast_aoc_add_unit_entry(decoded,
03444                (aoc_e->recorded.unit.item[i].number >= 0 ? 1 : 0),
03445                aoc_e->recorded.unit.item[i].number,
03446                (aoc_e->recorded.unit.item[i].type >= 0 ? 1 : 0),
03447                aoc_e->recorded.unit.item[i].type);
03448          }
03449       }
03450    }
03451 
03452    if (passthrough && owner && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
03453       ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
03454    }
03455 
03456    ast_aoc_manager_event(decoded, owner);
03457 
03458    ast_aoc_destroy_decoded(decoded);
03459    ast_aoc_destroy_encoded(encoded);
03460 }
03461 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03462 
03463 #if defined(HAVE_PRI_AOC_EVENTS)
03464 /*!
03465  * \internal
03466  * \brief send an AOC-S message on the current call
03467  *
03468  * \param pvt sig_pri private channel structure.
03469  * \param generic decoded ast AOC message
03470  *
03471  * \return Nothing
03472  *
03473  * \note Assumes that the PRI lock is already obtained.
03474  */
03475 static void sig_pri_aoc_s_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
03476 {
03477    struct pri_subcmd_aoc_s aoc_s = { 0, };
03478    const struct ast_aoc_s_entry *entry;
03479    int idx;
03480 
03481    for (idx = 0; idx < ast_aoc_s_get_count(decoded); idx++) {
03482       if (!(entry = ast_aoc_s_get_rate_info(decoded, idx))) {
03483          break;
03484       }
03485 
03486       aoc_s.item[idx].chargeable = sig_pri_aoc_charged_item_to_pri(entry->charged_item);
03487 
03488       switch (entry->rate_type) {
03489       case AST_AOC_RATE_TYPE_DURATION:
03490          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_DURATION;
03491          aoc_s.item[idx].rate.duration.amount.cost = entry->rate.duration.amount;
03492          aoc_s.item[idx].rate.duration.amount.multiplier =
03493             sig_pri_aoc_multiplier_from_ast(entry->rate.duration.multiplier);
03494          aoc_s.item[idx].rate.duration.time.length = entry->rate.duration.time;
03495          aoc_s.item[idx].rate.duration.time.scale =
03496             sig_pri_aoc_scale_to_pri(entry->rate.duration.time_scale);
03497          aoc_s.item[idx].rate.duration.granularity.length = entry->rate.duration.granularity_time;
03498          aoc_s.item[idx].rate.duration.granularity.scale =
03499             sig_pri_aoc_scale_to_pri(entry->rate.duration.granularity_time_scale);
03500          aoc_s.item[idx].rate.duration.charging_type = entry->rate.duration.charging_type;
03501 
03502          if (!ast_strlen_zero(entry->rate.duration.currency_name)) {
03503             ast_copy_string(aoc_s.item[idx].rate.duration.currency,
03504                entry->rate.duration.currency_name,
03505                sizeof(aoc_s.item[idx].rate.duration.currency));
03506          }
03507          break;
03508       case AST_AOC_RATE_TYPE_FLAT:
03509          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FLAT;
03510          aoc_s.item[idx].rate.flat.amount.cost = entry->rate.flat.amount;
03511          aoc_s.item[idx].rate.flat.amount.multiplier =
03512             sig_pri_aoc_multiplier_from_ast(entry->rate.flat.multiplier);
03513 
03514          if (!ast_strlen_zero(entry->rate.flat.currency_name)) {
03515             ast_copy_string(aoc_s.item[idx].rate.flat.currency,
03516                entry->rate.flat.currency_name,
03517                sizeof(aoc_s.item[idx].rate.flat.currency));
03518          }
03519          break;
03520       case AST_AOC_RATE_TYPE_VOLUME:
03521          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_VOLUME;
03522          aoc_s.item[idx].rate.volume.unit = entry->rate.volume.volume_unit;
03523          aoc_s.item[idx].rate.volume.amount.cost = entry->rate.volume.amount;
03524          aoc_s.item[idx].rate.volume.amount.multiplier =
03525             sig_pri_aoc_multiplier_from_ast(entry->rate.volume.multiplier);
03526 
03527          if (!ast_strlen_zero(entry->rate.volume.currency_name)) {
03528             ast_copy_string(aoc_s.item[idx].rate.volume.currency,
03529                entry->rate.volume.currency_name,
03530                sizeof(aoc_s.item[idx].rate.volume.currency));
03531          }
03532          break;
03533       case AST_AOC_RATE_TYPE_SPECIAL_CODE:
03534          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_SPECIAL_CODE;
03535          aoc_s.item[idx].rate.special = entry->rate.special_code;
03536          break;
03537       case AST_AOC_RATE_TYPE_FREE:
03538          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE;
03539          break;
03540       case AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
03541          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING;
03542          break;
03543       default:
03544       case AST_AOC_RATE_TYPE_NA:
03545          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_NOT_AVAILABLE;
03546          break;
03547       }
03548    }
03549    aoc_s.num_items = idx;
03550 
03551    /* if this rate should be sent as a response to an AOC-S request we will
03552     * have an aoc_s_request_invoke_id associated with this pvt */
03553    if (pvt->aoc_s_request_invoke_id_valid) {
03554       pri_aoc_s_request_response_send(pvt->pri->pri, pvt->call, pvt->aoc_s_request_invoke_id, &aoc_s);
03555       pvt->aoc_s_request_invoke_id_valid = 0;
03556    } else {
03557       pri_aoc_s_send(pvt->pri->pri, pvt->call, &aoc_s);
03558    }
03559 }
03560 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03561 
03562 #if defined(HAVE_PRI_AOC_EVENTS)
03563 /*!
03564  * \internal
03565  * \brief send an AOC-D message on the current call
03566  *
03567  * \param pvt sig_pri private channel structure.
03568  * \param generic decoded ast AOC message
03569  *
03570  * \return Nothing
03571  *
03572  * \note Assumes that the PRI lock is already obtained.
03573  */
03574 static void sig_pri_aoc_d_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
03575 {
03576    struct pri_subcmd_aoc_d aoc_d = { 0, };
03577 
03578    aoc_d.billing_accumulation = (ast_aoc_get_total_type(decoded) == AST_AOC_TOTAL) ? 1 : 0;
03579 
03580    switch (ast_aoc_get_billing_id(decoded)) {
03581    case AST_AOC_BILLING_NORMAL:
03582       aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NORMAL;
03583       break;
03584    case AST_AOC_BILLING_REVERSE_CHARGE:
03585       aoc_d.billing_id = PRI_AOC_D_BILLING_ID_REVERSE;
03586       break;
03587    case AST_AOC_BILLING_CREDIT_CARD:
03588       aoc_d.billing_id = PRI_AOC_D_BILLING_ID_CREDIT_CARD;
03589       break;
03590    case AST_AOC_BILLING_NA:
03591    default:
03592       aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NOT_AVAILABLE;
03593       break;
03594    }
03595 
03596    switch (ast_aoc_get_charge_type(decoded)) {
03597    case AST_AOC_CHARGE_FREE:
03598       aoc_d.charge = PRI_AOC_DE_CHARGE_FREE;
03599       break;
03600    case AST_AOC_CHARGE_CURRENCY:
03601       {
03602          const char *currency_name = ast_aoc_get_currency_name(decoded);
03603          aoc_d.charge = PRI_AOC_DE_CHARGE_CURRENCY;
03604          aoc_d.recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
03605          aoc_d.recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
03606          if (!ast_strlen_zero(currency_name)) {
03607             ast_copy_string(aoc_d.recorded.money.currency, currency_name, sizeof(aoc_d.recorded.money.currency));
03608          }
03609       }
03610       break;
03611    case AST_AOC_CHARGE_UNIT:
03612       {
03613          const struct ast_aoc_unit_entry *entry;
03614          int i;
03615          aoc_d.charge = PRI_AOC_DE_CHARGE_UNITS;
03616          for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
03617             if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_d.recorded.unit.item)) {
03618                if (entry->valid_amount) {
03619                   aoc_d.recorded.unit.item[i].number = entry->amount;
03620                } else {
03621                   aoc_d.recorded.unit.item[i].number = -1;
03622                }
03623                if (entry->valid_type) {
03624                   aoc_d.recorded.unit.item[i].type = entry->type;
03625                } else {
03626                   aoc_d.recorded.unit.item[i].type = -1;
03627                }
03628                aoc_d.recorded.unit.num_items++;
03629             } else {
03630                break;
03631             }
03632          }
03633       }
03634       break;
03635    case AST_AOC_CHARGE_NA:
03636    default:
03637       aoc_d.charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
03638       break;
03639    }
03640 
03641    pri_aoc_d_send(pvt->pri->pri, pvt->call, &aoc_d);
03642 }
03643 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03644 
03645 #if defined(HAVE_PRI_AOC_EVENTS)
03646 /*!
03647  * \internal
03648  * \brief send an AOC-E message on the current call
03649  *
03650  * \param pvt sig_pri private channel structure.
03651  * \param generic decoded ast AOC message
03652  *
03653  * \return Nothing
03654  *
03655  * \note Assumes that the PRI lock is already obtained.
03656  */
03657 static void sig_pri_aoc_e_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
03658 {
03659    struct pri_subcmd_aoc_e *aoc_e = &pvt->aoc_e;
03660    const struct ast_aoc_charging_association *ca = ast_aoc_get_association_info(decoded);
03661 
03662    memset(aoc_e, 0, sizeof(*aoc_e));
03663    pvt->holding_aoce = 1;
03664 
03665    switch (ca->charging_type) {
03666    case AST_AOC_CHARGING_ASSOCIATION_NUMBER:
03667       aoc_e->associated.charge.number.valid = 1;
03668       ast_copy_string(aoc_e->associated.charge.number.str,
03669          ca->charge.number.number,
03670          sizeof(aoc_e->associated.charge.number.str));
03671       aoc_e->associated.charge.number.plan = ca->charge.number.plan;
03672       aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER;
03673       break;
03674    case AST_AOC_CHARGING_ASSOCIATION_ID:
03675       aoc_e->associated.charge.id = ca->charge.id;
03676       aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_ID;
03677       break;
03678    case AST_AOC_CHARGING_ASSOCIATION_NA:
03679    default:
03680       break;
03681    }
03682 
03683    switch (ast_aoc_get_billing_id(decoded)) {
03684    case AST_AOC_BILLING_NORMAL:
03685       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NORMAL;
03686       break;
03687    case AST_AOC_BILLING_REVERSE_CHARGE:
03688       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_REVERSE;
03689       break;
03690    case AST_AOC_BILLING_CREDIT_CARD:
03691       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CREDIT_CARD;
03692       break;
03693    case AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL:
03694       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL;
03695       break;
03696    case AST_AOC_BILLING_CALL_FWD_BUSY:
03697       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY;
03698       break;
03699    case AST_AOC_BILLING_CALL_FWD_NO_REPLY:
03700       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY;
03701       break;
03702    case AST_AOC_BILLING_CALL_DEFLECTION:
03703       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_DEFLECTION;
03704       break;
03705    case AST_AOC_BILLING_CALL_TRANSFER:
03706       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_TRANSFER;
03707       break;
03708    case AST_AOC_BILLING_NA:
03709    default:
03710       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NOT_AVAILABLE;
03711       break;
03712    }
03713 
03714    switch (ast_aoc_get_charge_type(decoded)) {
03715    case AST_AOC_CHARGE_FREE:
03716       aoc_e->charge = PRI_AOC_DE_CHARGE_FREE;
03717       break;
03718    case AST_AOC_CHARGE_CURRENCY:
03719       {
03720          const char *currency_name = ast_aoc_get_currency_name(decoded);
03721          aoc_e->charge = PRI_AOC_DE_CHARGE_CURRENCY;
03722          aoc_e->recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
03723          aoc_e->recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
03724          if (!ast_strlen_zero(currency_name)) {
03725             ast_copy_string(aoc_e->recorded.money.currency, currency_name, sizeof(aoc_e->recorded.money.currency));
03726          }
03727       }
03728       break;
03729    case AST_AOC_CHARGE_UNIT:
03730       {
03731          const struct ast_aoc_unit_entry *entry;
03732          int i;
03733          aoc_e->charge = PRI_AOC_DE_CHARGE_UNITS;
03734          for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
03735             if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_e->recorded.unit.item)) {
03736                if (entry->valid_amount) {
03737                   aoc_e->recorded.unit.item[i].number = entry->amount;
03738                } else {
03739                   aoc_e->recorded.unit.item[i].number = -1;
03740                }
03741                if (entry->valid_type) {
03742                   aoc_e->recorded.unit.item[i].type = entry->type;
03743                } else {
03744                   aoc_e->recorded.unit.item[i].type = -1;
03745                }
03746                aoc_e->recorded.unit.num_items++;
03747             }
03748          }
03749       }
03750       break;
03751    case AST_AOC_CHARGE_NA:
03752    default:
03753       aoc_e->charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
03754       break;
03755    }
03756 }
03757 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03758 
03759 #if defined(HAVE_PRI_AOC_EVENTS)
03760 /*!
03761  * \internal
03762  * \brief send an AOC-E termination request on ast_channel and set
03763  * hangup delay.
03764  *
03765  * \param pri PRI span control structure.
03766  * \param chanpos Channel position in the span.
03767  * \param ms to delay hangup
03768  *
03769  * \note Assumes the pri->lock is already obtained.
03770  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
03771  *
03772  * \return Nothing
03773  */
03774 static void sig_pri_send_aoce_termination_request(struct sig_pri_span *pri, int chanpos, unsigned int ms)
03775 {
03776    struct sig_pri_chan *pvt;
03777    struct ast_aoc_decoded *decoded = NULL;
03778    struct ast_aoc_encoded *encoded = NULL;
03779    size_t encoded_size;
03780    struct timeval whentohangup = { 0, };
03781 
03782    sig_pri_lock_owner(pri, chanpos);
03783    pvt = pri->pvts[chanpos];
03784    if (!pvt->owner) {
03785       return;
03786    }
03787 
03788    if (!(decoded = ast_aoc_create(AST_AOC_REQUEST, 0, AST_AOC_REQUEST_E))) {
03789       ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
03790       goto cleanup_termination_request;
03791    }
03792 
03793    ast_aoc_set_termination_request(decoded);
03794 
03795    if (!(encoded = ast_aoc_encode(decoded, &encoded_size, pvt->owner))) {
03796       ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
03797       goto cleanup_termination_request;
03798    }
03799 
03800    /* convert ms to timeval */
03801    whentohangup.tv_usec = (ms % 1000) * 1000;
03802    whentohangup.tv_sec = ms / 1000;
03803 
03804    if (ast_queue_control_data(pvt->owner, AST_CONTROL_AOC, encoded, encoded_size)) {
03805       ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
03806       goto cleanup_termination_request;
03807    }
03808 
03809    pvt->waiting_for_aoce = 1;
03810    ast_channel_setwhentohangup_tv(pvt->owner, whentohangup);
03811    ast_log(LOG_DEBUG, "Delaying hangup on %s for aoc-e msg\n", pvt->owner->name);
03812 
03813 cleanup_termination_request:
03814    ast_channel_unlock(pvt->owner);
03815    ast_aoc_destroy_decoded(decoded);
03816    ast_aoc_destroy_encoded(encoded);
03817 }
03818 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03819 
03820 /*!
03821  * \internal
03822  * \brief TRUE if PRI event came in on a CIS call.
03823  * \since 1.8
03824  *
03825  * \param channel PRI encoded span/channel
03826  *
03827  * \retval non-zero if CIS call.
03828  */
03829 static int sig_pri_is_cis_call(int channel)
03830 {
03831    return channel != -1 && (channel & PRI_CIS_CALL);
03832 }
03833 
03834 /*!
03835  * \internal
03836  * \brief Handle the CIS associated PRI subcommand events.
03837  * \since 1.8
03838  *
03839  * \param pri PRI span control structure.
03840  * \param event_id PRI event id
03841  * \param subcmds Subcommands to process if any. (Could be NULL).
03842  * \param call_rsp libpri opaque call structure to send any responses toward.
03843  * Could be NULL either because it is not available or the call is for the
03844  * dummy call reference.  However, this should not be NULL in the cases that
03845  * need to use the pointer to send a response message back.
03846  *
03847  * \note Assumes the pri->lock is already obtained.
03848  *
03849  * \return Nothing
03850  */
03851 static void sig_pri_handle_cis_subcmds(struct sig_pri_span *pri, int event_id,
03852    const struct pri_subcommands *subcmds, q931_call *call_rsp)
03853 {
03854    int index;
03855 #if defined(HAVE_PRI_CCSS)
03856    struct ast_cc_agent *agent;
03857    struct sig_pri_cc_agent_prv *agent_prv;
03858    struct sig_pri_cc_monitor_instance *monitor;
03859 #endif   /* defined(HAVE_PRI_CCSS) */
03860 
03861    if (!subcmds) {
03862       return;
03863    }
03864    for (index = 0; index < subcmds->counter_subcmd; ++index) {
03865       const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
03866 
03867       switch (subcmd->cmd) {
03868 #if defined(STATUS_REQUEST_PLACE_HOLDER)
03869       case PRI_SUBCMD_STATUS_REQ:
03870       case PRI_SUBCMD_STATUS_REQ_RSP:
03871          /* Ignore for now. */
03872          break;
03873 #endif   /* defined(STATUS_REQUEST_PLACE_HOLDER) */
03874 #if defined(HAVE_PRI_CCSS)
03875       case PRI_SUBCMD_CC_REQ:
03876          agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_request.cc_id);
03877          if (!agent) {
03878             pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
03879             break;
03880          }
03881          if (!ast_cc_request_is_within_limits()) {
03882             if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
03883                5/* queue_full */)) {
03884                pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
03885             }
03886             ast_cc_failed(agent->core_id, "%s agent system CC queue full",
03887                sig_pri_cc_type_name);
03888             ao2_ref(agent, -1);
03889             break;
03890          }
03891          agent_prv = agent->private_data;
03892          agent_prv->cc_request_response_pending = 1;
03893          if (ast_cc_agent_accept_request(agent->core_id,
03894             "%s caller accepted CC offer.", sig_pri_cc_type_name)) {
03895             agent_prv->cc_request_response_pending = 0;
03896             if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
03897                2/* short_term_denial */)) {
03898                pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
03899             }
03900             ast_cc_failed(agent->core_id, "%s agent CC core request accept failed",
03901                sig_pri_cc_type_name);
03902          }
03903          ao2_ref(agent, -1);
03904          break;
03905 #endif   /* defined(HAVE_PRI_CCSS) */
03906 #if defined(HAVE_PRI_CCSS)
03907       case PRI_SUBCMD_CC_REQ_RSP:
03908          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
03909             subcmd->u.cc_request_rsp.cc_id);
03910          if (!monitor) {
03911             pri_cc_cancel(pri->pri, subcmd->u.cc_request_rsp.cc_id);
03912             break;
03913          }
03914          switch (subcmd->u.cc_request_rsp.status) {
03915          case 0:/* success */
03916             ast_cc_monitor_request_acked(monitor->core_id,
03917                "%s far end accepted CC request", sig_pri_cc_type_name);
03918             break;
03919          case 1:/* timeout */
03920             ast_verb(2, "core_id:%d %s CC request timeout\n", monitor->core_id,
03921                sig_pri_cc_type_name);
03922             ast_cc_monitor_failed(monitor->core_id, monitor->name,
03923                "%s CC request timeout", sig_pri_cc_type_name);
03924             break;
03925          case 2:/* error */
03926             ast_verb(2, "core_id:%d %s CC request error: %s\n", monitor->core_id,
03927                sig_pri_cc_type_name,
03928                pri_facility_error2str(subcmd->u.cc_request_rsp.fail_code));
03929             ast_cc_monitor_failed(monitor->core_id, monitor->name,
03930                "%s CC request error", sig_pri_cc_type_name);
03931             break;
03932          case 3:/* reject */
03933             ast_verb(2, "core_id:%d %s CC request reject: %s\n", monitor->core_id,
03934                sig_pri_cc_type_name,
03935                pri_facility_reject2str(subcmd->u.cc_request_rsp.fail_code));
03936             ast_cc_monitor_failed(monitor->core_id, monitor->name,
03937                "%s CC request reject", sig_pri_cc_type_name);
03938             break;
03939          default:
03940             ast_verb(2, "core_id:%d %s CC request unknown status %d\n",
03941                monitor->core_id, sig_pri_cc_type_name,
03942                subcmd->u.cc_request_rsp.status);
03943             ast_cc_monitor_failed(monitor->core_id, monitor->name,
03944                "%s CC request unknown status", sig_pri_cc_type_name);
03945             break;
03946          }
03947          ao2_ref(monitor, -1);
03948          break;
03949 #endif   /* defined(HAVE_PRI_CCSS) */
03950 #if defined(HAVE_PRI_CCSS)
03951       case PRI_SUBCMD_CC_REMOTE_USER_FREE:
03952          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
03953             subcmd->u.cc_remote_user_free.cc_id);
03954          if (!monitor) {
03955             pri_cc_cancel(pri->pri, subcmd->u.cc_remote_user_free.cc_id);
03956             break;
03957          }
03958          ast_cc_monitor_callee_available(monitor->core_id,
03959             "%s callee has become available", sig_pri_cc_type_name);
03960          ao2_ref(monitor, -1);
03961          break;
03962 #endif   /* defined(HAVE_PRI_CCSS) */
03963 #if defined(HAVE_PRI_CCSS)
03964       case PRI_SUBCMD_CC_B_FREE:
03965          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
03966             subcmd->u.cc_b_free.cc_id);
03967          if (!monitor) {
03968             pri_cc_cancel(pri->pri, subcmd->u.cc_b_free.cc_id);
03969             break;
03970          }
03971          ast_cc_monitor_party_b_free(monitor->core_id);
03972          ao2_ref(monitor, -1);
03973          break;
03974 #endif   /* defined(HAVE_PRI_CCSS) */
03975 #if defined(HAVE_PRI_CCSS)
03976       case PRI_SUBCMD_CC_STATUS_REQ:
03977          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
03978             subcmd->u.cc_status_req.cc_id);
03979          if (!monitor) {
03980             pri_cc_cancel(pri->pri, subcmd->u.cc_status_req.cc_id);
03981             break;
03982          }
03983          ast_cc_monitor_status_request(monitor->core_id);
03984          ao2_ref(monitor, -1);
03985          break;
03986 #endif   /* defined(HAVE_PRI_CCSS) */
03987 #if defined(HAVE_PRI_CCSS)
03988       case PRI_SUBCMD_CC_STATUS_REQ_RSP:
03989          agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status_req_rsp.cc_id);
03990          if (!agent) {
03991             pri_cc_cancel(pri->pri, subcmd->u.cc_status_req_rsp.cc_id);
03992             break;
03993          }
03994          ast_cc_agent_status_response(agent->core_id,
03995             subcmd->u.cc_status_req_rsp.status ? AST_DEVICE_INUSE
03996             : AST_DEVICE_NOT_INUSE);
03997          ao2_ref(agent, -1);
03998          break;
03999 #endif   /* defined(HAVE_PRI_CCSS) */
04000 #if defined(HAVE_PRI_CCSS)
04001       case PRI_SUBCMD_CC_STATUS:
04002          agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status.cc_id);
04003          if (!agent) {
04004             pri_cc_cancel(pri->pri, subcmd->u.cc_status.cc_id);
04005             break;
04006          }
04007          if (subcmd->u.cc_status.status) {
04008             ast_cc_agent_caller_busy(agent->core_id, "%s agent caller is busy",
04009                sig_pri_cc_type_name);
04010          } else {
04011             ast_cc_agent_caller_available(agent->core_id,
04012                "%s agent caller is available", sig_pri_cc_type_name);
04013          }
04014          ao2_ref(agent, -1);
04015          break;
04016 #endif   /* defined(HAVE_PRI_CCSS) */
04017 #if defined(HAVE_PRI_CCSS)
04018       case PRI_SUBCMD_CC_CANCEL:
04019          sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
04020             subcmd->u.cc_cancel.is_agent);
04021          break;
04022 #endif   /* defined(HAVE_PRI_CCSS) */
04023 #if defined(HAVE_PRI_CCSS)
04024       case PRI_SUBCMD_CC_STOP_ALERTING:
04025          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
04026             subcmd->u.cc_stop_alerting.cc_id);
04027          if (!monitor) {
04028             pri_cc_cancel(pri->pri, subcmd->u.cc_stop_alerting.cc_id);
04029             break;
04030          }
04031          ast_cc_monitor_stop_ringing(monitor->core_id);
04032          ao2_ref(monitor, -1);
04033          break;
04034 #endif   /* defined(HAVE_PRI_CCSS) */
04035 #if defined(HAVE_PRI_AOC_EVENTS)
04036       case PRI_SUBCMD_AOC_E:
04037          /* Queue AST_CONTROL_AOC frame */
04038          sig_pri_aoc_e_from_pri(&subcmd->u.aoc_e, NULL, 0);
04039          break;
04040 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04041       default:
04042          ast_debug(2,
04043             "Unknown CIS subcommand(%d) in %s event on span %d.\n",
04044             subcmd->cmd, pri_event2str(event_id), pri->span);
04045          break;
04046       }
04047    }
04048 }
04049 
04050 #if defined(HAVE_PRI_AOC_EVENTS)
04051 /*!
04052  * \internal
04053  * \brief detect if AOC-S subcmd is present.
04054  * \since 1.8
04055  *
04056  * \param subcmds Subcommands to process if any. (Could be NULL).
04057  *
04058  * \note Knowing whether or not an AOC-E subcmd is present on certain
04059  * PRI hangup events is necessary to determine what method to use to hangup
04060  * the ast_channel.  If an AOC-E subcmd just came in, then a new AOC-E was queued
04061  * on the ast_channel.  If a soft hangup is used, the AOC-E msg will never make it
04062  * across the bridge, but if a AST_CONTROL_HANGUP frame is queued behind it
04063  * we can ensure the AOC-E frame makes it to it's destination before the hangup
04064  * frame is read.
04065  *
04066  *
04067  * \retval 0 AOC-E is not present in subcmd list
04068  * \retval 1 AOC-E is present in subcmd list
04069  */
04070 static int detect_aoc_e_subcmd(const struct pri_subcommands *subcmds)
04071 {
04072    int i;
04073 
04074    if (!subcmds) {
04075       return 0;
04076    }
04077    for (i = 0; i < subcmds->counter_subcmd; ++i) {
04078       const struct pri_subcommand *subcmd = &subcmds->subcmd[i];
04079       if (subcmd->cmd == PRI_SUBCMD_AOC_E) {
04080          return 1;
04081       }
04082    }
04083    return 0;
04084 }
04085 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04086 
04087 /*!
04088  * \internal
04089  * \brief Handle the call associated PRI subcommand events.
04090  * \since 1.8
04091  *
04092  * \param pri PRI span control structure.
04093  * \param chanpos Channel position in the span.
04094  * \param event_id PRI event id
04095  * \param channel PRI encoded span/channel
04096  * \param subcmds Subcommands to process if any. (Could be NULL).
04097  * \param call_rsp libpri opaque call structure to send any responses toward.
04098  * Could be NULL either because it is not available or the call is for the
04099  * dummy call reference.  However, this should not be NULL in the cases that
04100  * need to use the pointer to send a response message back.
04101  *
04102  * \note Assumes the pri->lock is already obtained.
04103  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
04104  *
04105  * \return Nothing
04106  */
04107 static void sig_pri_handle_subcmds(struct sig_pri_span *pri, int chanpos, int event_id,
04108    int channel, const struct pri_subcommands *subcmds, q931_call *call_rsp)
04109 {
04110    int index;
04111    struct ast_channel *owner;
04112    struct ast_party_redirecting ast_redirecting;
04113 #if defined(HAVE_PRI_TRANSFER)
04114    struct xfer_rsp_data xfer_rsp;
04115 #endif   /* defined(HAVE_PRI_TRANSFER) */
04116 
04117    if (!subcmds) {
04118       return;
04119    }
04120    for (index = 0; index < subcmds->counter_subcmd; ++index) {
04121       const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
04122 
04123       switch (subcmd->cmd) {
04124       case PRI_SUBCMD_CONNECTED_LINE:
04125          sig_pri_lock_owner(pri, chanpos);
04126          owner = pri->pvts[chanpos]->owner;
04127          if (owner) {
04128             struct ast_party_connected_line ast_connected;
04129             int caller_id_update;
04130 
04131             /* Extract the connected line information */
04132             ast_party_connected_line_init(&ast_connected);
04133             sig_pri_party_id_convert(&ast_connected.id, &subcmd->u.connected_line.id,
04134                pri);
04135             ast_connected.id.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04136 
04137             caller_id_update = 0;
04138             if (ast_connected.id.name.str) {
04139                /* Save name for Caller-ID update */
04140                ast_copy_string(pri->pvts[chanpos]->cid_name,
04141                   ast_connected.id.name.str, sizeof(pri->pvts[chanpos]->cid_name));
04142                caller_id_update = 1;
04143             }
04144             if (ast_connected.id.number.str) {
04145                /* Save number for Caller-ID update */
04146                ast_copy_string(pri->pvts[chanpos]->cid_num,
04147                   ast_connected.id.number.str, sizeof(pri->pvts[chanpos]->cid_num));
04148                pri->pvts[chanpos]->cid_ton = ast_connected.id.number.plan;
04149                caller_id_update = 1;
04150             }
04151             ast_connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
04152 
04153             pri->pvts[chanpos]->cid_subaddr[0] = '\0';
04154 #if defined(HAVE_PRI_SUBADDR)
04155             if (ast_connected.id.subaddress.str) {
04156                ast_copy_string(pri->pvts[chanpos]->cid_subaddr,
04157                   ast_connected.id.subaddress.str,
04158                   sizeof(pri->pvts[chanpos]->cid_subaddr));
04159                caller_id_update = 1;
04160             }
04161 #endif   /* defined(HAVE_PRI_SUBADDR) */
04162             if (caller_id_update) {
04163                struct ast_party_caller ast_caller;
04164 
04165                pri->pvts[chanpos]->callingpres =
04166                   ast_party_id_presentation(&ast_connected.id);
04167                sig_pri_set_caller_id(pri->pvts[chanpos]);
04168 
04169                ast_party_caller_set_init(&ast_caller, &owner->caller);
04170                ast_caller.id = ast_connected.id;
04171                ast_caller.ani = ast_connected.id;
04172                ast_channel_set_caller_event(owner, &ast_caller, NULL);
04173 
04174                /* Update the connected line information on the other channel */
04175                if (event_id != PRI_EVENT_RING) {
04176                   /* This connected_line update was not from a SETUP message. */
04177                   ast_channel_queue_connected_line_update(owner, &ast_connected,
04178                      NULL);
04179                }
04180             }
04181 
04182             ast_party_connected_line_free(&ast_connected);
04183             ast_channel_unlock(owner);
04184          }
04185          break;
04186       case PRI_SUBCMD_REDIRECTING:
04187          sig_pri_lock_owner(pri, chanpos);
04188          owner = pri->pvts[chanpos]->owner;
04189          if (owner) {
04190             sig_pri_redirecting_convert(&ast_redirecting, &subcmd->u.redirecting,
04191                &owner->redirecting, pri);
04192             ast_redirecting.from.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04193             ast_redirecting.to.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04194 
04195 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
04196 
04197             ast_channel_set_redirecting(owner, &ast_redirecting, NULL);
04198             if (event_id != PRI_EVENT_RING) {
04199                /* This redirection was not from a SETUP message. */
04200                ast_channel_queue_redirecting_update(owner, &ast_redirecting, NULL);
04201             }
04202             ast_party_redirecting_free(&ast_redirecting);
04203 
04204             ast_channel_unlock(owner);
04205          }
04206          break;
04207 #if defined(HAVE_PRI_CALL_REROUTING)
04208       case PRI_SUBCMD_REROUTING:
04209          sig_pri_lock_owner(pri, chanpos);
04210          owner = pri->pvts[chanpos]->owner;
04211          if (owner) {
04212             struct pri_party_redirecting pri_deflection;
04213 
04214             if (!call_rsp) {
04215                ast_log(LOG_WARNING,
04216                   "Span %d: %s tried CallRerouting/CallDeflection to '%s' without call!\n",
04217                   pri->span, owner->name, subcmd->u.rerouting.deflection.to.number.str);
04218                ast_channel_unlock(owner);
04219                break;
04220             }
04221             if (ast_strlen_zero(subcmd->u.rerouting.deflection.to.number.str)) {
04222                ast_log(LOG_WARNING,
04223                   "Span %d: %s tried CallRerouting/CallDeflection to empty number!\n",
04224                   pri->span, owner->name);
04225                pri_rerouting_rsp(pri->pri, call_rsp, subcmd->u.rerouting.invoke_id,
04226                   PRI_REROUTING_RSP_INVALID_NUMBER);
04227                ast_channel_unlock(owner);
04228                break;
04229             }
04230 
04231             ast_verb(3, "Span %d: %s is CallRerouting/CallDeflection to '%s'.\n",
04232                pri->span, owner->name, subcmd->u.rerouting.deflection.to.number.str);
04233 
04234             /*
04235              * Send back positive ACK to CallRerouting/CallDeflection.
04236              *
04237              * Note:  This call will be hungup by the core when it processes
04238              * the call_forward string.
04239              */
04240             pri_rerouting_rsp(pri->pri, call_rsp, subcmd->u.rerouting.invoke_id,
04241                PRI_REROUTING_RSP_OK_CLEAR);
04242 
04243             pri_deflection = subcmd->u.rerouting.deflection;
04244 
04245             /* Adjust the deflecting to number based upon the subscription option. */
04246             switch (subcmd->u.rerouting.subscription_option) {
04247             case 0:  /* noNotification */
04248             case 1:  /* notificationWithoutDivertedToNr */
04249                /* Delete the number because the far end is not supposed to see it. */
04250                pri_deflection.to.number.presentation =
04251                   PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
04252                pri_deflection.to.number.plan =
04253                   (PRI_TON_UNKNOWN << 4) | PRI_NPI_E163_E164;
04254                pri_deflection.to.number.str[0] = '\0';
04255                break;
04256             case 2:  /* notificationWithDivertedToNr */
04257                break;
04258             case 3:  /* notApplicable */
04259             default:
04260                break;
04261             }
04262             sig_pri_redirecting_convert(&ast_redirecting, &pri_deflection,
04263                &owner->redirecting, pri);
04264             ast_redirecting.from.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04265             ast_redirecting.to.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04266             ast_channel_set_redirecting(owner, &ast_redirecting, NULL);
04267             ast_party_redirecting_free(&ast_redirecting);
04268 
04269             /* Request the core to forward to the new number. */
04270             ast_string_field_set(owner, call_forward,
04271                subcmd->u.rerouting.deflection.to.number.str);
04272 
04273             /* Wake up the channel. */
04274             ast_queue_frame(owner, &ast_null_frame);
04275 
04276             ast_channel_unlock(owner);
04277          }
04278          break;
04279 #endif   /* defined(HAVE_PRI_CALL_REROUTING) */
04280 #if defined(HAVE_PRI_CCSS)
04281       case PRI_SUBCMD_CC_AVAILABLE:
04282          sig_pri_lock_owner(pri, chanpos);
04283          owner = pri->pvts[chanpos]->owner;
04284          if (owner) {
04285             enum ast_cc_service_type service;
04286 
04287             switch (event_id) {
04288             case PRI_EVENT_RINGING:
04289                service = AST_CC_CCNR;
04290                break;
04291             case PRI_EVENT_HANGUP_REQ:
04292                /* We will assume that the cause was busy/congestion. */
04293                service = AST_CC_CCBS;
04294                break;
04295             default:
04296                service = AST_CC_NONE;
04297                break;
04298             }
04299             if (service == AST_CC_NONE
04300                || sig_pri_cc_available(pri, chanpos, subcmd->u.cc_available.cc_id,
04301                service)) {
04302                pri_cc_cancel(pri->pri, subcmd->u.cc_available.cc_id);
04303             }
04304             ast_channel_unlock(owner);
04305          } else {
04306             /* No asterisk channel. */
04307             pri_cc_cancel(pri->pri, subcmd->u.cc_available.cc_id);
04308          }
04309          break;
04310 #endif   /* defined(HAVE_PRI_CCSS) */
04311 #if defined(HAVE_PRI_CCSS)
04312       case PRI_SUBCMD_CC_CALL:
04313          sig_pri_lock_owner(pri, chanpos);
04314          owner = pri->pvts[chanpos]->owner;
04315          if (owner) {
04316             struct ast_cc_agent *agent;
04317 
04318             agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_call.cc_id);
04319             if (agent) {
04320                ast_setup_cc_recall_datastore(owner, agent->core_id);
04321                ast_cc_agent_set_interfaces_chanvar(owner);
04322                ast_cc_agent_recalling(agent->core_id,
04323                   "%s caller is attempting recall", sig_pri_cc_type_name);
04324                ao2_ref(agent, -1);
04325             }
04326 
04327             ast_channel_unlock(owner);
04328          }
04329          break;
04330 #endif   /* defined(HAVE_PRI_CCSS) */
04331 #if defined(HAVE_PRI_CCSS)
04332       case PRI_SUBCMD_CC_CANCEL:
04333          sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
04334             subcmd->u.cc_cancel.is_agent);
04335          break;
04336 #endif   /* defined(HAVE_PRI_CCSS) */
04337 #if defined(HAVE_PRI_TRANSFER)
04338       case PRI_SUBCMD_TRANSFER_CALL:
04339          if (!call_rsp) {
04340             /* Should never happen. */
04341             ast_log(LOG_ERROR,
04342                "Call transfer subcommand without call to send response!\n");
04343             break;
04344          }
04345 
04346          sig_pri_unlock_private(pri->pvts[chanpos]);
04347          xfer_rsp.pri = pri;
04348          xfer_rsp.call = call_rsp;
04349          xfer_rsp.invoke_id = subcmd->u.transfer.invoke_id;
04350          sig_pri_attempt_transfer(pri,
04351             subcmd->u.transfer.call_1, subcmd->u.transfer.is_call_1_held,
04352             subcmd->u.transfer.call_2, subcmd->u.transfer.is_call_2_held,
04353             sig_pri_transfer_rsp, &xfer_rsp);
04354          sig_pri_lock_private(pri->pvts[chanpos]);
04355          break;
04356 #endif   /* defined(HAVE_PRI_TRANSFER) */
04357 #if defined(HAVE_PRI_AOC_EVENTS)
04358       case PRI_SUBCMD_AOC_S:
04359          sig_pri_lock_owner(pri, chanpos);
04360          owner = pri->pvts[chanpos]->owner;
04361          if (owner) {
04362             sig_pri_aoc_s_from_pri(&subcmd->u.aoc_s, owner,
04363                (pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S));
04364             ast_channel_unlock(owner);
04365          }
04366          break;
04367 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04368 #if defined(HAVE_PRI_AOC_EVENTS)
04369       case PRI_SUBCMD_AOC_D:
04370          sig_pri_lock_owner(pri, chanpos);
04371          owner = pri->pvts[chanpos]->owner;
04372          if (owner) {
04373             /* Queue AST_CONTROL_AOC frame on channel */
04374             sig_pri_aoc_d_from_pri(&subcmd->u.aoc_d, owner,
04375                (pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D));
04376             ast_channel_unlock(owner);
04377          }
04378          break;
04379 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04380 #if defined(HAVE_PRI_AOC_EVENTS)
04381       case PRI_SUBCMD_AOC_E:
04382          sig_pri_lock_owner(pri, chanpos);
04383          owner = pri->pvts[chanpos]->owner;
04384          /* Queue AST_CONTROL_AOC frame */
04385          sig_pri_aoc_e_from_pri(&subcmd->u.aoc_e, owner,
04386             (pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E));
04387          if (owner) {
04388             ast_channel_unlock(owner);
04389          }
04390          break;
04391 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04392 #if defined(HAVE_PRI_AOC_EVENTS)
04393       case PRI_SUBCMD_AOC_CHARGING_REQ:
04394          sig_pri_lock_owner(pri, chanpos);
04395          owner = pri->pvts[chanpos]->owner;
04396          if (owner) {
04397             sig_pri_aoc_request_from_pri(&subcmd->u.aoc_request, pri->pvts[chanpos],
04398                call_rsp);
04399             ast_channel_unlock(owner);
04400          }
04401          break;
04402 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04403 #if defined(HAVE_PRI_AOC_EVENTS)
04404       case PRI_SUBCMD_AOC_CHARGING_REQ_RSP:
04405          /*
04406           * An AOC request response may contain an AOC-S rate list.
04407           * If this is the case handle this just like we
04408           * would an incoming AOC-S msg.
04409           */
04410          if (subcmd->u.aoc_request_response.valid_aoc_s) {
04411             sig_pri_lock_owner(pri, chanpos);
04412             owner = pri->pvts[chanpos]->owner;
04413             if (owner) {
04414                sig_pri_aoc_s_from_pri(&subcmd->u.aoc_request_response.aoc_s, owner,
04415                   (pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S));
04416                ast_channel_unlock(owner);
04417             }
04418          }
04419          break;
04420 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04421 #if defined(HAVE_PRI_MCID)
04422       case PRI_SUBCMD_MCID_REQ:
04423          sig_pri_lock_owner(pri, chanpos);
04424          owner = pri->pvts[chanpos]->owner;
04425          sig_pri_mcid_event(pri, &subcmd->u.mcid_req, owner);
04426          if (owner) {
04427             ast_channel_unlock(owner);
04428          }
04429          break;
04430 #endif   /* defined(HAVE_PRI_MCID) */
04431 #if defined(HAVE_PRI_MCID)
04432       case PRI_SUBCMD_MCID_RSP:
04433          /* Ignore for now. */
04434          break;
04435 #endif   /* defined(HAVE_PRI_MCID) */
04436       default:
04437          ast_debug(2,
04438             "Unknown call subcommand(%d) in %s event on channel %d/%d on span %d.\n",
04439             subcmd->cmd, pri_event2str(event_id), PRI_SPAN(channel),
04440             PRI_CHANNEL(channel), pri->span);
04441          break;
04442       }
04443    }
04444 }
04445 
04446 #if defined(HAVE_PRI_CALL_HOLD)
04447 /*!
04448  * \internal
04449  * \brief Handle the hold event from libpri.
04450  * \since 1.8
04451  *
04452  * \param pri PRI span control structure.
04453  * \param ev Hold event received.
04454  *
04455  * \note Assumes the pri->lock is already obtained.
04456  *
04457  * \retval 0 on success.
04458  * \retval -1 on error.
04459  */
04460 static int sig_pri_handle_hold(struct sig_pri_span *pri, pri_event *ev)
04461 {
04462    int retval;
04463    int chanpos_old;
04464    int chanpos_new;
04465    struct ast_channel *owner;
04466 
04467    chanpos_old = pri_find_principle_by_call(pri, ev->hold.call);
04468    if (chanpos_old < 0) {
04469       ast_log(LOG_WARNING, "Span %d: Received HOLD for unknown call.\n", pri->span);
04470       return -1;
04471    }
04472    if (pri->pvts[chanpos_old]->no_b_channel) {
04473       /* Call is already on hold or is call waiting call. */
04474       return -1;
04475    }
04476 
04477    chanpos_new = -1;
04478 
04479    sig_pri_lock_private(pri->pvts[chanpos_old]);
04480    sig_pri_lock_owner(pri, chanpos_old);
04481    owner = pri->pvts[chanpos_old]->owner;
04482    if (!owner) {
04483       goto done_with_private;
04484    }
04485    if (pri->pvts[chanpos_old]->call_level != SIG_PRI_CALL_LEVEL_CONNECT) {
04486       /*
04487        * Make things simple.  Don't allow placing a call on hold that
04488        * is not connected.
04489        */
04490       goto done_with_owner;
04491    }
04492    chanpos_new = pri_find_empty_nobch(pri);
04493    if (chanpos_new < 0) {
04494       /* No hold channel available. */
04495       goto done_with_owner;
04496    }
04497    sig_pri_handle_subcmds(pri, chanpos_old, ev->e, ev->hold.channel, ev->hold.subcmds,
04498       ev->hold.call);
04499    chanpos_new = pri_fixup_principle(pri, chanpos_new, ev->hold.call);
04500    if (chanpos_new < 0) {
04501       /* Should never happen. */
04502    } else {
04503       struct ast_frame f = { AST_FRAME_CONTROL, };
04504 
04505       /*
04506        * Things are in an odd state here so we cannot use pri_queue_control().
04507        * However, we already have the owner lock so we can simply queue the frame.
04508        */
04509       f.subclass.integer = AST_CONTROL_HOLD;
04510       ast_queue_frame(owner, &f);
04511    }
04512 
04513 done_with_owner:;
04514    ast_channel_unlock(owner);
04515 done_with_private:;
04516    sig_pri_unlock_private(pri->pvts[chanpos_old]);
04517 
04518    if (chanpos_new < 0) {
04519       retval = -1;
04520    } else {
04521       sig_pri_span_devstate_changed(pri);
04522       retval = 0;
04523    }
04524 
04525    return retval;
04526 }
04527 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
04528 
04529 #if defined(HAVE_PRI_CALL_HOLD)
04530 /*!
04531  * \internal
04532  * \brief Handle the retrieve event from libpri.
04533  * \since 1.8
04534  *
04535  * \param pri PRI span control structure.
04536  * \param ev Retrieve event received.
04537  *
04538  * \note Assumes the pri->lock is already obtained.
04539  *
04540  * \return Nothing
04541  */
04542 static void sig_pri_handle_retrieve(struct sig_pri_span *pri, pri_event *ev)
04543 {
04544    int chanpos;
04545 
04546    if (!(ev->retrieve.channel & PRI_HELD_CALL)) {
04547       /* The call is not currently held. */
04548       pri_retrieve_rej(pri->pri, ev->retrieve.call,
04549          PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED);
04550       return;
04551    }
04552    if (pri_find_principle_by_call(pri, ev->retrieve.call) < 0) {
04553       ast_log(LOG_WARNING, "Span %d: Received RETRIEVE for unknown call.\n", pri->span);
04554       pri_retrieve_rej(pri->pri, ev->retrieve.call,
04555          PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED);
04556       return;
04557    }
04558    if (PRI_CHANNEL(ev->retrieve.channel) == 0xFF) {
04559       chanpos = pri_find_empty_chan(pri, 1);
04560    } else {
04561       chanpos = pri_find_principle(pri,
04562          ev->retrieve.channel & ~PRI_HELD_CALL, ev->retrieve.call);
04563       if (ev->retrieve.flexible
04564          && (chanpos < 0 || !sig_pri_is_chan_available(pri->pvts[chanpos]))) {
04565          /*
04566           * Channel selection is flexible and the requested channel
04567           * is bad or not available.  Pick another channel.
04568           */
04569          chanpos = pri_find_empty_chan(pri, 1);
04570       }
04571    }
04572    if (chanpos < 0) {
04573       pri_retrieve_rej(pri->pri, ev->retrieve.call,
04574          ev->retrieve.flexible ? PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION
04575          : PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
04576       return;
04577    }
04578    chanpos = pri_fixup_principle(pri, chanpos, ev->retrieve.call);
04579    if (chanpos < 0) {
04580       /* Channel is already in use. */
04581       pri_retrieve_rej(pri->pri, ev->retrieve.call,
04582          PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
04583       return;
04584    }
04585    sig_pri_lock_private(pri->pvts[chanpos]);
04586    sig_pri_handle_subcmds(pri, chanpos, ev->e, ev->retrieve.channel,
04587       ev->retrieve.subcmds, ev->retrieve.call);
04588    pri_queue_control(pri, chanpos, AST_CONTROL_UNHOLD);
04589    sig_pri_unlock_private(pri->pvts[chanpos]);
04590    pri_retrieve_ack(pri->pri, ev->retrieve.call,
04591       PVT_TO_CHANNEL(pri->pvts[chanpos]));
04592    sig_pri_span_devstate_changed(pri);
04593 }
04594 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
04595 
04596 static void *pri_dchannel(void *vpri)
04597 {
04598    struct sig_pri_span *pri = vpri;
04599    pri_event *e;
04600    struct pollfd fds[SIG_PRI_NUM_DCHANS];
04601    int res;
04602    int chanpos = 0;
04603    int x;
04604    enum sig_pri_law law;
04605    struct ast_channel *c;
04606    struct timeval tv, lowest, *next;
04607    int doidling=0;
04608    char *cc;
04609    time_t t;
04610    int i, which=-1;
04611    int numdchans;
04612    pthread_t threadid;
04613    char ani2str[6];
04614    char plancallingnum[AST_MAX_EXTENSION];
04615    char plancallingani[AST_MAX_EXTENSION];
04616    char calledtonstr[10];
04617    struct timeval lastidle = { 0, 0 };
04618    pthread_t p;
04619    struct ast_channel *idle;
04620    char idlen[80];
04621    int nextidle = -1;
04622    int haveidles;
04623    int activeidles;
04624    unsigned int len;
04625 
04626    gettimeofday(&lastidle, NULL);
04627    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
04628 
04629    if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
04630       /* Need to do idle dialing, check to be sure though */
04631       cc = strchr(pri->idleext, '@');
04632       if (cc) {
04633          *cc = '\0';
04634          cc++;
04635          ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
04636 #if 0
04637          /* Extensions may not be loaded yet */
04638          if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
04639             ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
04640          else
04641 #endif
04642             doidling = 1;
04643       } else
04644          ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
04645    }
04646    for (;;) {
04647       for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
04648          if (!pri->dchans[i])
04649             break;
04650          fds[i].fd = pri->fds[i];
04651          fds[i].events = POLLIN | POLLPRI;
04652          fds[i].revents = 0;
04653       }
04654       numdchans = i;
04655       time(&t);
04656       ast_mutex_lock(&pri->lock);
04657       if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->sig != SIG_BRI_PTMP) && (pri->resetinterval > 0)) {
04658          if (pri->resetting && pri_is_up(pri)) {
04659             if (pri->resetpos < 0) {
04660                pri_check_restart(pri);
04661                if (pri->resetting) {
04662                   sig_pri_span_devstate_changed(pri);
04663                }
04664             }
04665          } else {
04666             if (!pri->resetting  && (t - pri->lastreset) >= pri->resetinterval) {
04667                pri->resetting = 1;
04668                pri->resetpos = -1;
04669             }
04670          }
04671       }
04672       /* Look for any idle channels if appropriate */
04673       if (doidling && pri_is_up(pri)) {
04674          nextidle = -1;
04675          haveidles = 0;
04676          activeidles = 0;
04677          for (x = pri->numchans; x >= 0; x--) {
04678             if (pri->pvts[x] && !pri->pvts[x]->no_b_channel) {
04679                if (sig_pri_is_chan_available(pri->pvts[x])) {
04680                   if (haveidles < pri->minunused) {
04681                      haveidles++;
04682                   } else {
04683                      nextidle = x;
04684                      break;
04685                   }
04686                } else if (pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
04687                   activeidles++;
04688                }
04689             }
04690          }
04691          if (nextidle > -1) {
04692             if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
04693                /* Don't create a new idle call more than once per second */
04694                snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
04695                pri->pvts[nextidle]->allocated = 1;
04696                /*
04697                 * Release the PRI lock while we create the channel so other
04698                 * threads can send D channel messages.
04699                 */
04700                ast_mutex_unlock(&pri->lock);
04701                /*
04702                 * We already have the B channel reserved for this call.  We
04703                 * just need to make sure that sig_pri_hangup() has completed
04704                 * cleaning up before continuing.
04705                 */
04706                sig_pri_lock_private(pri->pvts[nextidle]);
04707                sig_pri_unlock_private(pri->pvts[nextidle]);
04708                idle = sig_pri_request(pri->pvts[nextidle], SIG_PRI_ULAW, NULL, 0);
04709                ast_mutex_lock(&pri->lock);
04710                if (idle) {
04711                   pri->pvts[nextidle]->isidlecall = 1;
04712                   if (ast_pthread_create_background(&p, NULL, do_idle_thread, pri->pvts[nextidle])) {
04713                      ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
04714                      ast_mutex_unlock(&pri->lock);
04715                      ast_hangup(idle);
04716                      ast_mutex_lock(&pri->lock);
04717                   }
04718                } else {
04719                   pri->pvts[nextidle]->allocated = 0;
04720                   ast_log(LOG_WARNING, "Unable to request channel 'DAHDI/%s' for idle call\n", idlen);
04721                }
04722                gettimeofday(&lastidle, NULL);
04723             }
04724          } else if ((haveidles < pri->minunused) &&
04725             (activeidles > pri->minidle)) {
04726             /* Mark something for hangup if there is something
04727                that can be hungup */
04728             for (x = pri->numchans; x >= 0; x--) {
04729                /* find a candidate channel */
04730                if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
04731                   pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04732                   haveidles++;
04733                   /* Stop if we have enough idle channels or
04734                     can't spare any more active idle ones */
04735                   if ((haveidles >= pri->minunused) ||
04736                      (activeidles <= pri->minidle))
04737                      break;
04738                }
04739             }
04740          }
04741       }
04742       /* Start with reasonable max */
04743       if (doidling || pri->resetting) {
04744          /*
04745           * Make sure we stop at least once per second if we're
04746           * monitoring idle channels
04747           */
04748          lowest = ast_tv(1, 0);
04749       } else {
04750          /* Don't poll for more than 60 seconds */
04751          lowest = ast_tv(60, 0);
04752       }
04753       for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
04754          if (!pri->dchans[i]) {
04755             /* We scanned all D channels on this span. */
04756             break;
04757          }
04758          next = pri_schedule_next(pri->dchans[i]);
04759          if (next) {
04760             /* We need relative time here */
04761             tv = ast_tvsub(*next, ast_tvnow());
04762             if (tv.tv_sec < 0) {
04763                /*
04764                 * A timer has already expired.
04765                 * By definition zero time is the lowest so we can quit early.
04766                 */
04767                lowest = ast_tv(0, 0);
04768                break;
04769             }
04770             if (ast_tvcmp(tv, lowest) < 0) {
04771                lowest = tv;
04772             }
04773          }
04774       }
04775       ast_mutex_unlock(&pri->lock);
04776 
04777       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
04778       pthread_testcancel();
04779       e = NULL;
04780       res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
04781       pthread_testcancel();
04782       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
04783 
04784       ast_mutex_lock(&pri->lock);
04785       if (!res) {
04786          for (which = 0; which < SIG_PRI_NUM_DCHANS; which++) {
04787             if (!pri->dchans[which])
04788                break;
04789             /* Just a timeout, run the scheduler */
04790             e = pri_schedule_run(pri->dchans[which]);
04791             if (e)
04792                break;
04793          }
04794       } else if (res > -1) {
04795          for (which = 0; which < SIG_PRI_NUM_DCHANS; which++) {
04796             if (!pri->dchans[which])
04797                break;
04798             if (fds[which].revents & POLLPRI) {
04799                sig_pri_handle_dchan_exception(pri, which);
04800             } else if (fds[which].revents & POLLIN) {
04801                e = pri_check_event(pri->dchans[which]);
04802             }
04803             if (e)
04804                break;
04805          }
04806       } else if (errno != EINTR)
04807          ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
04808 
04809       if (e) {
04810          if (pri->debug) {
04811             ast_verbose("Span %d: Processing event %s\n",
04812                pri->span, pri_event2str(e->e));
04813          }
04814 
04815          if (e->e != PRI_EVENT_DCHAN_DOWN) {
04816             if (!(pri->dchanavail[which] & DCHAN_UP)) {
04817                ast_verb(2, "%s D-Channel on span %d up\n", pri_order(which), pri->span);
04818             }
04819             pri->dchanavail[which] |= DCHAN_UP;
04820          } else {
04821             if (pri->dchanavail[which] & DCHAN_UP) {
04822                ast_verb(2, "%s D-Channel on span %d down\n", pri_order(which), pri->span);
04823             }
04824             pri->dchanavail[which] &= ~DCHAN_UP;
04825          }
04826 
04827          if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
04828             /* Must be an NFAS group that has the secondary dchan active */
04829             pri->pri = pri->dchans[which];
04830 
04831          switch (e->e) {
04832          case PRI_EVENT_DCHAN_UP:
04833             pri->no_d_channels = 0;
04834             if (!pri->pri) {
04835                pri_find_dchan(pri);
04836             }
04837 
04838             /* Note presense of D-channel */
04839             time(&pri->lastreset);
04840 
04841             /* Restart in 5 seconds */
04842             if (pri->resetinterval > -1) {
04843                pri->lastreset -= pri->resetinterval;
04844                pri->lastreset += 5;
04845             }
04846             /* Take the channels from inalarm condition */
04847             pri->resetting = 0;
04848             for (i = 0; i < pri->numchans; i++) {
04849                if (pri->pvts[i]) {
04850                   sig_pri_set_alarm(pri->pvts[i], 0);
04851                }
04852             }
04853             sig_pri_span_devstate_changed(pri);
04854             break;
04855          case PRI_EVENT_DCHAN_DOWN:
04856             pri_find_dchan(pri);
04857             if (!pri_is_up(pri)) {
04858                if (pri->sig == SIG_BRI_PTMP) {
04859                   /*
04860                    * For PTMP connections with non-persistent layer 2 we want to
04861                    * *not* declare inalarm unless there actually is an alarm.
04862                    */
04863                   break;
04864                }
04865                /* Hangup active channels and put them in alarm mode */
04866                pri->resetting = 0;
04867                for (i = 0; i < pri->numchans; i++) {
04868                   struct sig_pri_chan *p = pri->pvts[i];
04869 
04870                   if (p) {
04871                      if (pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
04872                         /* T309 is not enabled : destroy calls when alarm occurs */
04873                         if (p->call) {
04874                            pri_destroycall(p->pri->pri, p->call);
04875                            p->call = NULL;
04876                         }
04877                         if (p->owner)
04878                            p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04879                      }
04880                      sig_pri_set_alarm(p, 1);
04881                   }
04882                }
04883                sig_pri_span_devstate_changed(pri);
04884             }
04885             break;
04886          case PRI_EVENT_RESTART:
04887             if (e->restart.channel > -1 && PRI_CHANNEL(e->restart.channel) != 0xFF) {
04888                chanpos = pri_find_principle(pri, e->restart.channel, NULL);
04889                if (chanpos < 0)
04890                   ast_log(LOG_WARNING,
04891                      "Span %d: Restart requested on odd/unavailable channel number %d/%d\n",
04892                      pri->span, PRI_SPAN(e->restart.channel),
04893                      PRI_CHANNEL(e->restart.channel));
04894                else {
04895                   int skipit = 0;
04896 #if defined(HAVE_PRI_SERVICE_MESSAGES)
04897                   unsigned why;
04898 
04899                   why = pri->pvts[chanpos]->service_status;
04900                   if (why) {
04901                      ast_log(LOG_NOTICE,
04902                         "Span %d: Channel %d/%d out-of-service (reason: %s), ignoring RESTART\n",
04903                         pri->span, PRI_SPAN(e->restart.channel),
04904                         PRI_CHANNEL(e->restart.channel),
04905                         (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
04906                      skipit = 1;
04907                   }
04908 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
04909                   sig_pri_lock_private(pri->pvts[chanpos]);
04910                   if (!skipit) {
04911                      ast_verb(3, "Span %d: Channel %d/%d restarted\n", pri->span,
04912                         PRI_SPAN(e->restart.channel),
04913                         PRI_CHANNEL(e->restart.channel));
04914                      if (pri->pvts[chanpos]->call) {
04915                         pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
04916                         pri->pvts[chanpos]->call = NULL;
04917                      }
04918                   }
04919                   /* Force soft hangup if appropriate */
04920                   if (pri->pvts[chanpos]->owner)
04921                      pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04922                   sig_pri_unlock_private(pri->pvts[chanpos]);
04923                }
04924             } else {
04925                ast_verb(3, "Restart requested on entire span %d\n", pri->span);
04926                for (x = 0; x < pri->numchans; x++)
04927                   if (pri->pvts[x]) {
04928                      sig_pri_lock_private(pri->pvts[x]);
04929                      if (pri->pvts[x]->call) {
04930                         pri_destroycall(pri->pri, pri->pvts[x]->call);
04931                         pri->pvts[x]->call = NULL;
04932                      }
04933                      if (pri->pvts[x]->owner)
04934                         pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04935                      sig_pri_unlock_private(pri->pvts[x]);
04936                   }
04937             }
04938             sig_pri_span_devstate_changed(pri);
04939             break;
04940          case PRI_EVENT_KEYPAD_DIGIT:
04941             if (sig_pri_is_cis_call(e->digit.channel)) {
04942                sig_pri_handle_cis_subcmds(pri, e->e, e->digit.subcmds,
04943                   e->digit.call);
04944                break;
04945             }
04946             chanpos = pri_find_principle_by_call(pri, e->digit.call);
04947             if (chanpos < 0) {
04948                ast_log(LOG_WARNING,
04949                   "Span %d: Received keypad digits for unknown call.\n", pri->span);
04950                break;
04951             }
04952             sig_pri_lock_private(pri->pvts[chanpos]);
04953             sig_pri_handle_subcmds(pri, chanpos, e->e, e->digit.channel,
04954                e->digit.subcmds, e->digit.call);
04955             /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
04956             if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
04957                && pri->pvts[chanpos]->owner) {
04958                /* how to do that */
04959                int digitlen = strlen(e->digit.digits);
04960                int i;
04961 
04962                for (i = 0; i < digitlen; i++) {
04963                   struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->digit.digits[i], };
04964 
04965                   pri_queue_frame(pri, chanpos, &f);
04966                }
04967             }
04968             sig_pri_unlock_private(pri->pvts[chanpos]);
04969             break;
04970 
04971          case PRI_EVENT_INFO_RECEIVED:
04972             if (sig_pri_is_cis_call(e->ring.channel)) {
04973                sig_pri_handle_cis_subcmds(pri, e->e, e->ring.subcmds,
04974                   e->ring.call);
04975                break;
04976             }
04977             chanpos = pri_find_principle_by_call(pri, e->ring.call);
04978             if (chanpos < 0) {
04979                ast_log(LOG_WARNING,
04980                   "Span %d: Received INFORMATION for unknown call.\n", pri->span);
04981                break;
04982             }
04983             sig_pri_lock_private(pri->pvts[chanpos]);
04984             sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
04985                e->ring.subcmds, e->ring.call);
04986             /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
04987             if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
04988                && pri->pvts[chanpos]->owner) {
04989                /* how to do that */
04990                int digitlen = strlen(e->ring.callednum);
04991                int i;
04992 
04993                for (i = 0; i < digitlen; i++) {
04994                   struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->ring.callednum[i], };
04995 
04996                   pri_queue_frame(pri, chanpos, &f);
04997                }
04998             }
04999             sig_pri_unlock_private(pri->pvts[chanpos]);
05000             break;
05001 #if defined(HAVE_PRI_SERVICE_MESSAGES)
05002          case PRI_EVENT_SERVICE:
05003             chanpos = pri_find_principle(pri, e->service.channel, NULL);
05004             if (chanpos < 0) {
05005                ast_log(LOG_WARNING, "Received service change status %d on unconfigured channel %d/%d span %d\n",
05006                   e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
05007             } else {
05008                char db_chan_name[20];
05009                char db_answer[5];
05010                int ch;
05011                unsigned *why;
05012 
05013                ch = pri->pvts[chanpos]->channel;
05014                snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->span, ch);
05015                why = &pri->pvts[chanpos]->service_status;
05016                switch (e->service.changestatus) {
05017                case 0: /* in-service */
05018                   /* Far end wants to be in service now. */
05019                   ast_db_del(db_chan_name, SRVST_DBKEY);
05020                   *why &= ~SRVST_FAREND;
05021                   if (*why) {
05022                      snprintf(db_answer, sizeof(db_answer), "%s:%u",
05023                         SRVST_TYPE_OOS, *why);
05024                      ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
05025                   } else {
05026                      sig_pri_span_devstate_changed(pri);
05027                   }
05028                   break;
05029                case 2: /* out-of-service */
05030                   /* Far end wants to be out-of-service now. */
05031                   ast_db_del(db_chan_name, SRVST_DBKEY);
05032                   *why |= SRVST_FAREND;
05033                   snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS,
05034                      *why);
05035                   ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
05036                   sig_pri_span_devstate_changed(pri);
05037                   break;
05038                default:
05039                   ast_log(LOG_ERROR, "Huh?  changestatus is: %d\n", e->service.changestatus);
05040                   break;
05041                }
05042                ast_log(LOG_NOTICE, "Channel %d/%d span %d (logical: %d) received a change of service message, status '%d'\n",
05043                   PRI_SPAN(e->service.channel), PRI_CHANNEL(e->service.channel), pri->span, ch, e->service.changestatus);
05044             }
05045             break;
05046          case PRI_EVENT_SERVICE_ACK:
05047             chanpos = pri_find_principle(pri, e->service_ack.channel, NULL);
05048             if (chanpos < 0) {
05049                ast_log(LOG_WARNING, "Received service acknowledge change status '%d' on unconfigured channel %d/%d span %d\n",
05050                   e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
05051             } else {
05052                ast_debug(2, "Channel %d/%d span %d received a change os service acknowledgement message, status '%d'\n",
05053                   PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span, e->service_ack.changestatus);
05054             }
05055             break;
05056 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
05057          case PRI_EVENT_RING:
05058             if (!ast_strlen_zero(pri->msn_list)
05059                && !sig_pri_msn_match(pri->msn_list, e->ring.callednum)) {
05060                /* The call is not for us so ignore it. */
05061                ast_verb(3,
05062                   "Ignoring call to '%s' on span %d.  Its not in the MSN list: %s\n",
05063                   e->ring.callednum, pri->span, pri->msn_list);
05064                pri_destroycall(pri->pri, e->ring.call);
05065                break;
05066             }
05067             if (sig_pri_is_cis_call(e->ring.channel)) {
05068                sig_pri_handle_cis_subcmds(pri, e->e, e->ring.subcmds,
05069                   e->ring.call);
05070                break;
05071             }
05072             chanpos = pri_find_principle_by_call(pri, e->ring.call);
05073             if (-1 < chanpos) {
05074                /* Libpri has already filtered out duplicate SETUPs. */
05075                ast_log(LOG_WARNING,
05076                   "Span %d: Got SETUP with duplicate call ptr (%p).  Dropping call.\n",
05077                   pri->span, e->ring.call);
05078                pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_TEMPORARY_FAILURE);
05079                break;
05080             }
05081             if (e->ring.channel == -1 || PRI_CHANNEL(e->ring.channel) == 0xFF) {
05082                /* Any channel requested. */
05083                chanpos = pri_find_empty_chan(pri, 1);
05084             } else if (PRI_CHANNEL(e->ring.channel) == 0x00) {
05085                /* No channel specified. */
05086 #if defined(HAVE_PRI_CALL_WAITING)
05087                if (!pri->allow_call_waiting_calls)
05088 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05089                {
05090                   /* We will not accept incoming call waiting calls. */
05091                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
05092                   break;
05093                }
05094 #if defined(HAVE_PRI_CALL_WAITING)
05095                chanpos = pri_find_empty_nobch(pri);
05096                if (chanpos < 0) {
05097                   /* We could not find/create a call interface. */
05098                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
05099                   break;
05100                }
05101                /* Setup the call interface to use. */
05102                sig_pri_init_config(pri->pvts[chanpos], pri);
05103 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05104             } else {
05105                /* A channel is specified. */
05106                chanpos = pri_find_principle(pri, e->ring.channel, e->ring.call);
05107                if (chanpos < 0) {
05108                   ast_log(LOG_WARNING,
05109                      "Span %d: SETUP on unconfigured channel %d/%d\n",
05110                      pri->span, PRI_SPAN(e->ring.channel),
05111                      PRI_CHANNEL(e->ring.channel));
05112                } else {
05113                   switch (pri->pvts[chanpos]->resetting) {
05114                   case SIG_PRI_RESET_IDLE:
05115                      break;
05116                   case SIG_PRI_RESET_ACTIVE:
05117                      /*
05118                       * The peer may have lost the expected ack or not received the
05119                       * RESTART yet.
05120                       */
05121                      pri->pvts[chanpos]->resetting = SIG_PRI_RESET_NO_ACK;
05122                      break;
05123                   case SIG_PRI_RESET_NO_ACK:
05124                      /* The peer likely is not going to ack the RESTART. */
05125                      ast_debug(1,
05126                         "Span %d: Second SETUP while waiting for RESTART ACKNOWLEDGE on channel %d/%d\n",
05127                         pri->span, PRI_SPAN(e->ring.channel),
05128                         PRI_CHANNEL(e->ring.channel));
05129 
05130                      /* Assume we got the ack. */
05131                      pri->pvts[chanpos]->resetting = SIG_PRI_RESET_IDLE;
05132                      if (pri->resetting) {
05133                         /* Go on to the next idle channel to RESTART. */
05134                         pri_check_restart(pri);
05135                      }
05136                      break;
05137                   }
05138                   if (!sig_pri_is_chan_available(pri->pvts[chanpos])) {
05139                      /* This is where we handle initial glare */
05140                      ast_debug(1,
05141                         "Span %d: SETUP requested unavailable channel %d/%d.  Attempting to renegotiate.\n",
05142                         pri->span, PRI_SPAN(e->ring.channel),
05143                         PRI_CHANNEL(e->ring.channel));
05144                      chanpos = -1;
05145                   }
05146                }
05147 #if defined(ALWAYS_PICK_CHANNEL)
05148                if (e->ring.flexible) {
05149                   chanpos = -1;
05150                }
05151 #endif   /* defined(ALWAYS_PICK_CHANNEL) */
05152                if (chanpos < 0 && e->ring.flexible) {
05153                   /* We can try to pick another channel. */
05154                   chanpos = pri_find_empty_chan(pri, 1);
05155                }
05156             }
05157             if (chanpos < 0) {
05158                if (e->ring.flexible) {
05159                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
05160                } else {
05161                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
05162                }
05163                break;
05164             }
05165 
05166             sig_pri_lock_private(pri->pvts[chanpos]);
05167 
05168             /* Mark channel as in use so noone else will steal it. */
05169             pri->pvts[chanpos]->call = e->ring.call;
05170 
05171             /* Use plancallingnum as a scratch buffer since it is initialized next. */
05172             apply_plan_to_existing_number(plancallingnum, sizeof(plancallingnum), pri,
05173                e->ring.redirectingnum, e->ring.callingplanrdnis);
05174             sig_pri_set_rdnis(pri->pvts[chanpos], plancallingnum);
05175 
05176             /* Setup caller-id info */
05177             apply_plan_to_existing_number(plancallingnum, sizeof(plancallingnum), pri,
05178                e->ring.callingnum, e->ring.callingplan);
05179             pri->pvts[chanpos]->cid_ani2 = 0;
05180             if (pri->pvts[chanpos]->use_callerid) {
05181                ast_shrink_phone_number(plancallingnum);
05182                ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
05183 #ifdef PRI_ANI
05184                apply_plan_to_existing_number(plancallingani, sizeof(plancallingani),
05185                   pri, e->ring.callingani, e->ring.callingplanani);
05186                ast_shrink_phone_number(plancallingani);
05187                ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani,
05188                   sizeof(pri->pvts[chanpos]->cid_ani));
05189 #endif
05190                pri->pvts[chanpos]->cid_subaddr[0] = '\0';
05191 #if defined(HAVE_PRI_SUBADDR)
05192                if (e->ring.calling.subaddress.valid) {
05193                   struct ast_party_subaddress calling_subaddress;
05194 
05195                   ast_party_subaddress_init(&calling_subaddress);
05196                   sig_pri_set_subaddress(&calling_subaddress,
05197                      &e->ring.calling.subaddress);
05198                   if (calling_subaddress.str) {
05199                      ast_copy_string(pri->pvts[chanpos]->cid_subaddr,
05200                         calling_subaddress.str,
05201                         sizeof(pri->pvts[chanpos]->cid_subaddr));
05202                   }
05203                   ast_party_subaddress_free(&calling_subaddress);
05204                }
05205 #endif /* defined(HAVE_PRI_SUBADDR) */
05206                ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
05207                pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
05208                pri->pvts[chanpos]->callingpres = e->ring.callingpres;
05209                if (e->ring.ani2 >= 0) {
05210                   pri->pvts[chanpos]->cid_ani2 = e->ring.ani2;
05211                }
05212             } else {
05213                pri->pvts[chanpos]->cid_num[0] = '\0';
05214                pri->pvts[chanpos]->cid_subaddr[0] = '\0';
05215                pri->pvts[chanpos]->cid_ani[0] = '\0';
05216                pri->pvts[chanpos]->cid_name[0] = '\0';
05217                pri->pvts[chanpos]->cid_ton = 0;
05218                pri->pvts[chanpos]->callingpres = 0;
05219             }
05220 
05221             /* Setup the user tag for party id's from this device for this call. */
05222             if (pri->append_msn_to_user_tag) {
05223                snprintf(pri->pvts[chanpos]->user_tag,
05224                   sizeof(pri->pvts[chanpos]->user_tag), "%s_%s",
05225                   pri->initial_user_tag,
05226                   pri->nodetype == PRI_NETWORK
05227                      ? plancallingnum : e->ring.callednum);
05228             } else {
05229                ast_copy_string(pri->pvts[chanpos]->user_tag,
05230                   pri->initial_user_tag, sizeof(pri->pvts[chanpos]->user_tag));
05231             }
05232 
05233             sig_pri_set_caller_id(pri->pvts[chanpos]);
05234 
05235             /* Set DNID on all incoming calls -- even immediate */
05236             sig_pri_set_dnid(pri->pvts[chanpos], e->ring.callednum);
05237 
05238             /* If immediate=yes go to s|1 */
05239             if (pri->pvts[chanpos]->immediate) {
05240                ast_verb(3, "Going to extension s|1 because of immediate=yes\n");
05241                pri->pvts[chanpos]->exten[0] = 's';
05242                pri->pvts[chanpos]->exten[1] = '\0';
05243             }
05244             /* Get called number */
05245             else if (!ast_strlen_zero(e->ring.callednum)) {
05246                ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
05247             } else if (pri->overlapdial)
05248                pri->pvts[chanpos]->exten[0] = '\0';
05249             else {
05250                /* Some PRI circuits are set up to send _no_ digits.  Handle them as 's'. */
05251                pri->pvts[chanpos]->exten[0] = 's';
05252                pri->pvts[chanpos]->exten[1] = '\0';
05253             }
05254             /* No number yet, but received "sending complete"? */
05255             if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
05256                ast_verb(3, "Going to extension s|1 because of Complete received\n");
05257                pri->pvts[chanpos]->exten[0] = 's';
05258                pri->pvts[chanpos]->exten[1] = '\0';
05259             }
05260 
05261             /* Make sure extension exists (or in overlap dial mode, can exist) */
05262             if (((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
05263                ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
05264                int could_match_more;
05265                int need_dialtone;
05266 
05267                /* Select audio companding mode. */
05268                switch (e->ring.layer1) {
05269                case PRI_LAYER_1_ALAW:
05270                   law = SIG_PRI_ALAW;
05271                   break;
05272                case PRI_LAYER_1_ULAW:
05273                   law = SIG_PRI_ULAW;
05274                   break;
05275                default:
05276                   /* This is a data call to us. */
05277                   law = SIG_PRI_DEFLAW;
05278                   break;
05279                }
05280 
05281                could_match_more = !e->ring.complete
05282                   && (pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
05283                   && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context,
05284                      pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num);
05285 
05286                need_dialtone = could_match_more
05287                   /*
05288                    * Must explicitly check the digital capability this
05289                    * way instead of checking the pvt->digital flag
05290                    * because the flag hasn't been set yet.
05291                    */
05292                   && !(e->ring.ctype & AST_TRANS_CAP_DIGITAL)
05293                   && !pri->pvts[chanpos]->no_b_channel
05294                   && (!strlen(pri->pvts[chanpos]->exten)
05295                      || ast_ignore_pattern(pri->pvts[chanpos]->context,
05296                         pri->pvts[chanpos]->exten));
05297 
05298                if (e->ring.complete || !(pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
05299                   /* Just announce proceeding */
05300                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
05301                   pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
05302                } else if (pri->switchtype == PRI_SWITCH_GR303_TMC) {
05303                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_CONNECT;
05304                   pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
05305                } else {
05306                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_OVERLAP;
05307 #if defined(HAVE_PRI_SETUP_ACK_INBAND)
05308                   pri_setup_ack(pri->pri, e->ring.call,
05309                      PVT_TO_CHANNEL(pri->pvts[chanpos]), 1, need_dialtone);
05310 #else /* !defined(HAVE_PRI_SETUP_ACK_INBAND) */
05311                   pri_need_more_info(pri->pri, e->ring.call,
05312                      PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
05313 #endif   /* !defined(HAVE_PRI_SETUP_ACK_INBAND) */
05314                }
05315 
05316                /* Start PBX */
05317                if (could_match_more) {
05318                   /*
05319                    * Release the PRI lock while we create the channel so other
05320                    * threads can send D channel messages.  We must also release
05321                    * the private lock to prevent deadlock while creating the
05322                    * channel.
05323                    */
05324                   sig_pri_unlock_private(pri->pvts[chanpos]);
05325                   ast_mutex_unlock(&pri->lock);
05326                   c = sig_pri_new_ast_channel(pri->pvts[chanpos],
05327                      AST_STATE_RESERVED, law, e->ring.ctype,
05328                      pri->pvts[chanpos]->exten, NULL);
05329                   ast_mutex_lock(&pri->lock);
05330                   sig_pri_lock_private(pri->pvts[chanpos]);
05331                   if (c) {
05332 #if defined(HAVE_PRI_SUBADDR)
05333                      if (e->ring.calling.subaddress.valid) {
05334                         /* Set Calling Subaddress */
05335                         sig_pri_lock_owner(pri, chanpos);
05336                         sig_pri_set_subaddress(
05337                            &pri->pvts[chanpos]->owner->caller.id.subaddress,
05338                            &e->ring.calling.subaddress);
05339                         if (!e->ring.calling.subaddress.type
05340                            && !ast_strlen_zero(
05341                               (char *) e->ring.calling.subaddress.data)) {
05342                            /* NSAP */
05343                            pbx_builtin_setvar_helper(c, "CALLINGSUBADDR",
05344                               (char *) e->ring.calling.subaddress.data);
05345                         }
05346                         ast_channel_unlock(c);
05347                      }
05348                      if (e->ring.called_subaddress.valid) {
05349                         /* Set Called Subaddress */
05350                         sig_pri_lock_owner(pri, chanpos);
05351                         sig_pri_set_subaddress(
05352                            &pri->pvts[chanpos]->owner->dialed.subaddress,
05353                            &e->ring.called_subaddress);
05354                         if (!e->ring.called_subaddress.type
05355                            && !ast_strlen_zero(
05356                               (char *) e->ring.called_subaddress.data)) {
05357                            /* NSAP */
05358                            pbx_builtin_setvar_helper(c, "CALLEDSUBADDR",
05359                               (char *) e->ring.called_subaddress.data);
05360                         }
05361                         ast_channel_unlock(c);
05362                      }
05363 #else
05364                      if (!ast_strlen_zero(e->ring.callingsubaddr)) {
05365                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
05366                      }
05367 #endif /* !defined(HAVE_PRI_SUBADDR) */
05368                      if (e->ring.ani2 >= 0) {
05369                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
05370                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
05371                      }
05372 
05373 #ifdef SUPPORT_USERUSER
05374                      if (!ast_strlen_zero(e->ring.useruserinfo)) {
05375                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
05376                      }
05377 #endif
05378 
05379                      snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
05380                      pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
05381                      ast_channel_lock(c);
05382                      c->dialed.number.plan = e->ring.calledplan;
05383                      ast_channel_unlock(c);
05384 
05385                      if (e->ring.redirectingreason >= 0) {
05386                         /* This is now just a status variable.  Use REDIRECTING() dialplan function. */
05387                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
05388                      }
05389 #if defined(HAVE_PRI_REVERSE_CHARGE)
05390                      pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
05391 #endif
05392 #if defined(HAVE_PRI_SETUP_KEYPAD)
05393                      ast_copy_string(pri->pvts[chanpos]->keypad_digits,
05394                         e->ring.keypad_digits,
05395                         sizeof(pri->pvts[chanpos]->keypad_digits));
05396 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
05397 
05398                      sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
05399                         e->ring.subcmds, e->ring.call);
05400 
05401 #if !defined(HAVE_PRI_SETUP_ACK_INBAND)
05402                      if (need_dialtone) {
05403                         /* Indicate that we are providing dialtone. */
05404                         pri->pvts[chanpos]->progress = 1;/* No need to send plain PROGRESS again. */
05405 #ifdef HAVE_PRI_PROG_W_CAUSE
05406                         pri_progress_with_cause(pri->pri, e->ring.call,
05407                            PVT_TO_CHANNEL(pri->pvts[chanpos]), 1, -1);/* no cause at all */
05408 #else
05409                         pri_progress(pri->pri, e->ring.call,
05410                            PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
05411 #endif
05412                      }
05413 #endif   /* !defined(HAVE_PRI_SETUP_ACK_INBAND) */
05414                   }
05415                   if (c && !ast_pthread_create_detached(&threadid, NULL, pri_ss_thread, pri->pvts[chanpos])) {
05416                      ast_verb(3, "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
05417                         plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
05418                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
05419                   } else {
05420                      ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
05421                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
05422                      if (c) {
05423                         /* Avoid deadlock while destroying channel */
05424                         sig_pri_unlock_private(pri->pvts[chanpos]);
05425                         ast_mutex_unlock(&pri->lock);
05426                         ast_hangup(c);
05427                         ast_mutex_lock(&pri->lock);
05428                      } else {
05429                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
05430                         pri->pvts[chanpos]->call = NULL;
05431                         sig_pri_unlock_private(pri->pvts[chanpos]);
05432                         sig_pri_span_devstate_changed(pri);
05433                      }
05434                      break;
05435                   }
05436                } else {
05437                   /*
05438                    * Release the PRI lock while we create the channel so other
05439                    * threads can send D channel messages.  We must also release
05440                    * the private lock to prevent deadlock while creating the
05441                    * channel.
05442                    */
05443                   sig_pri_unlock_private(pri->pvts[chanpos]);
05444                   ast_mutex_unlock(&pri->lock);
05445                   c = sig_pri_new_ast_channel(pri->pvts[chanpos],
05446                      AST_STATE_RING, law, e->ring.ctype,
05447                      pri->pvts[chanpos]->exten, NULL);
05448                   ast_mutex_lock(&pri->lock);
05449                   sig_pri_lock_private(pri->pvts[chanpos]);
05450                   if (c) {
05451                      /*
05452                       * It is reasonably safe to set the following
05453                       * channel variables while the PRI and DAHDI private
05454                       * structures are locked.  The PBX has not been
05455                       * started yet and it is unlikely that any other task
05456                       * will do anything with the channel we have just
05457                       * created.
05458                       */
05459 #if defined(HAVE_PRI_SUBADDR)
05460                      if (e->ring.calling.subaddress.valid) {
05461                         /* Set Calling Subaddress */
05462                         sig_pri_lock_owner(pri, chanpos);
05463                         sig_pri_set_subaddress(
05464                            &pri->pvts[chanpos]->owner->caller.id.subaddress,
05465                            &e->ring.calling.subaddress);
05466                         if (!e->ring.calling.subaddress.type
05467                            && !ast_strlen_zero(
05468                               (char *) e->ring.calling.subaddress.data)) {
05469                            /* NSAP */
05470                            pbx_builtin_setvar_helper(c, "CALLINGSUBADDR",
05471                               (char *) e->ring.calling.subaddress.data);
05472                         }
05473                         ast_channel_unlock(c);
05474                      }
05475                      if (e->ring.called_subaddress.valid) {
05476                         /* Set Called Subaddress */
05477                         sig_pri_lock_owner(pri, chanpos);
05478                         sig_pri_set_subaddress(
05479                            &pri->pvts[chanpos]->owner->dialed.subaddress,
05480                            &e->ring.called_subaddress);
05481                         if (!e->ring.called_subaddress.type
05482                            && !ast_strlen_zero(
05483                               (char *) e->ring.called_subaddress.data)) {
05484                            /* NSAP */
05485                            pbx_builtin_setvar_helper(c, "CALLEDSUBADDR",
05486                               (char *) e->ring.called_subaddress.data);
05487                         }
05488                         ast_channel_unlock(c);
05489                      }
05490 #else
05491                      if (!ast_strlen_zero(e->ring.callingsubaddr)) {
05492                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
05493                      }
05494 #endif /* !defined(HAVE_PRI_SUBADDR) */
05495                      if (e->ring.ani2 >= 0) {
05496                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
05497                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
05498                      }
05499 
05500 #ifdef SUPPORT_USERUSER
05501                      if (!ast_strlen_zero(e->ring.useruserinfo)) {
05502                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
05503                      }
05504 #endif
05505 
05506                      if (e->ring.redirectingreason >= 0) {
05507                         /* This is now just a status variable.  Use REDIRECTING() dialplan function. */
05508                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
05509                      }
05510 #if defined(HAVE_PRI_REVERSE_CHARGE)
05511                      pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
05512 #endif
05513 #if defined(HAVE_PRI_SETUP_KEYPAD)
05514                      ast_copy_string(pri->pvts[chanpos]->keypad_digits,
05515                         e->ring.keypad_digits,
05516                         sizeof(pri->pvts[chanpos]->keypad_digits));
05517 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
05518 
05519                      snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
05520                      pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
05521                      ast_channel_lock(c);
05522                      c->dialed.number.plan = e->ring.calledplan;
05523                      ast_channel_unlock(c);
05524 
05525                      sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
05526                         e->ring.subcmds, e->ring.call);
05527                   }
05528                   if (c && !ast_pbx_start(c)) {
05529                      ast_verb(3, "Accepting call from '%s' to '%s' on channel %d/%d, span %d\n",
05530                         plancallingnum, pri->pvts[chanpos]->exten,
05531                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
05532                      sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
05533                   } else {
05534                      ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
05535                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
05536                      if (c) {
05537                         /* Avoid deadlock while destroying channel */
05538                         sig_pri_unlock_private(pri->pvts[chanpos]);
05539                         ast_mutex_unlock(&pri->lock);
05540                         ast_hangup(c);
05541                         ast_mutex_lock(&pri->lock);
05542                      } else {
05543                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
05544                         pri->pvts[chanpos]->call = NULL;
05545                         sig_pri_unlock_private(pri->pvts[chanpos]);
05546                         sig_pri_span_devstate_changed(pri);
05547                      }
05548                      break;
05549                   }
05550                }
05551             } else {
05552                ast_verb(3,
05553                   "Span %d: Extension %s@%s does not exist.  Rejecting call from '%s'.\n",
05554                   pri->span, pri->pvts[chanpos]->exten, pri->pvts[chanpos]->context,
05555                   pri->pvts[chanpos]->cid_num);
05556                pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_UNALLOCATED);
05557                pri->pvts[chanpos]->call = NULL;
05558                pri->pvts[chanpos]->exten[0] = '\0';
05559                sig_pri_unlock_private(pri->pvts[chanpos]);
05560                sig_pri_span_devstate_changed(pri);
05561                break;
05562             }
05563             sig_pri_unlock_private(pri->pvts[chanpos]);
05564             break;
05565          case PRI_EVENT_RINGING:
05566             if (sig_pri_is_cis_call(e->ringing.channel)) {
05567                sig_pri_handle_cis_subcmds(pri, e->e, e->ringing.subcmds,
05568                   e->ringing.call);
05569                break;
05570             }
05571             chanpos = pri_find_fixup_principle(pri, e->ringing.channel,
05572                e->ringing.call);
05573             if (chanpos < 0) {
05574                break;
05575             }
05576             sig_pri_lock_private(pri->pvts[chanpos]);
05577 
05578             sig_pri_handle_subcmds(pri, chanpos, e->e, e->ringing.channel,
05579                e->ringing.subcmds, e->ringing.call);
05580             sig_pri_cc_generic_check(pri, chanpos, AST_CC_CCNR);
05581             sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
05582             sig_pri_lock_owner(pri, chanpos);
05583             if (pri->pvts[chanpos]->owner) {
05584                ast_setstate(pri->pvts[chanpos]->owner, AST_STATE_RINGING);
05585                ast_channel_unlock(pri->pvts[chanpos]->owner);
05586             }
05587             pri_queue_control(pri, chanpos, AST_CONTROL_RINGING);
05588             if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_ALERTING) {
05589                pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_ALERTING;
05590             }
05591 
05592             if (!pri->pvts[chanpos]->progress
05593                && !pri->pvts[chanpos]->no_b_channel
05594 #ifdef PRI_PROGRESS_MASK
05595                && (e->ringing.progressmask
05596                   & (PRI_PROG_CALL_NOT_E2E_ISDN | PRI_PROG_INBAND_AVAILABLE))
05597 #else
05598                && e->ringing.progress == 8
05599 #endif
05600                ) {
05601                /* Bring voice path up */
05602                pri_queue_control(pri, chanpos, AST_CONTROL_PROGRESS);
05603                pri->pvts[chanpos]->progress = 1;
05604                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05605                sig_pri_open_media(pri->pvts[chanpos]);
05606             }
05607 
05608 #ifdef SUPPORT_USERUSER
05609             if (!ast_strlen_zero(e->ringing.useruserinfo)) {
05610                struct ast_channel *owner;
05611 
05612                sig_pri_lock_owner(pri, chanpos);
05613                owner = pri->pvts[chanpos]->owner;
05614                if (owner) {
05615                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
05616                      e->ringing.useruserinfo);
05617                   ast_channel_unlock(owner);
05618                }
05619             }
05620 #endif
05621 
05622             sig_pri_unlock_private(pri->pvts[chanpos]);
05623             break;
05624          case PRI_EVENT_PROGRESS:
05625             if (sig_pri_is_cis_call(e->proceeding.channel)) {
05626                sig_pri_handle_cis_subcmds(pri, e->e, e->proceeding.subcmds,
05627                   e->proceeding.call);
05628                break;
05629             }
05630             chanpos = pri_find_fixup_principle(pri, e->proceeding.channel,
05631                e->proceeding.call);
05632             if (chanpos < 0) {
05633                break;
05634             }
05635             sig_pri_lock_private(pri->pvts[chanpos]);
05636             sig_pri_handle_subcmds(pri, chanpos, e->e, e->proceeding.channel,
05637                e->proceeding.subcmds, e->proceeding.call);
05638 
05639             if (e->proceeding.cause > -1) {
05640                ast_verb(3, "PROGRESS with cause code %d received\n", e->proceeding.cause);
05641 
05642                /* Work around broken, out of spec USER_BUSY cause in a progress message */
05643                if (e->proceeding.cause == AST_CAUSE_USER_BUSY) {
05644                   if (pri->pvts[chanpos]->owner) {
05645                      ast_verb(3, "PROGRESS with 'user busy' received, signaling AST_CONTROL_BUSY instead of AST_CONTROL_PROGRESS\n");
05646 
05647                      pri->pvts[chanpos]->owner->hangupcause = e->proceeding.cause;
05648                      pri_queue_control(pri, chanpos, AST_CONTROL_BUSY);
05649                   }
05650                }
05651             }
05652 
05653             if (!pri->pvts[chanpos]->progress
05654                && !pri->pvts[chanpos]->no_b_channel
05655 #ifdef PRI_PROGRESS_MASK
05656                && (e->proceeding.progressmask
05657                   & (PRI_PROG_CALL_NOT_E2E_ISDN | PRI_PROG_INBAND_AVAILABLE))
05658 #else
05659                && e->proceeding.progress == 8
05660 #endif
05661                ) {
05662                /* Bring voice path up */
05663                ast_debug(1,
05664                   "Queuing frame from PRI_EVENT_PROGRESS on channel %d/%d span %d\n",
05665                   pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,
05666                   pri->span);
05667                pri_queue_control(pri, chanpos, AST_CONTROL_PROGRESS);
05668                pri->pvts[chanpos]->progress = 1;
05669                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05670                sig_pri_open_media(pri->pvts[chanpos]);
05671             }
05672             sig_pri_unlock_private(pri->pvts[chanpos]);
05673             break;
05674          case PRI_EVENT_PROCEEDING:
05675             if (sig_pri_is_cis_call(e->proceeding.channel)) {
05676                sig_pri_handle_cis_subcmds(pri, e->e, e->proceeding.subcmds,
05677                   e->proceeding.call);
05678                break;
05679             }
05680             chanpos = pri_find_fixup_principle(pri, e->proceeding.channel,
05681                e->proceeding.call);
05682             if (chanpos < 0) {
05683                break;
05684             }
05685             sig_pri_lock_private(pri->pvts[chanpos]);
05686             sig_pri_handle_subcmds(pri, chanpos, e->e, e->proceeding.channel,
05687                e->proceeding.subcmds, e->proceeding.call);
05688             if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING) {
05689                pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
05690                ast_debug(1,
05691                   "Queuing frame from PRI_EVENT_PROCEEDING on channel %d/%d span %d\n",
05692                   pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,
05693                   pri->span);
05694                pri_queue_control(pri, chanpos, AST_CONTROL_PROCEEDING);
05695             }
05696             if (!pri->pvts[chanpos]->progress
05697                && !pri->pvts[chanpos]->no_b_channel
05698 #ifdef PRI_PROGRESS_MASK
05699                /*
05700                 * We only care about PRI_PROG_INBAND_AVAILABLE to open the
05701                 * voice path.
05702                 *
05703                 * We explicitly DO NOT want to check PRI_PROG_CALL_NOT_E2E_ISDN
05704                 * because it will mess up ISDN to SIP interoperability for
05705                 * the ALERTING message.
05706                 */
05707                && (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE)
05708 #else
05709                && e->proceeding.progress == 8
05710 #endif
05711                ) {
05712                /* Bring voice path up */
05713                pri_queue_control(pri, chanpos, AST_CONTROL_PROGRESS);
05714                pri->pvts[chanpos]->progress = 1;
05715                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05716                sig_pri_open_media(pri->pvts[chanpos]);
05717             } else if (pri->inband_on_proceeding) {
05718                /*
05719                 * XXX This is to accomodate a broken switch that sends a
05720                 * PROCEEDING without any progress indication ie for
05721                 * inband audio.  This should be part of the conditional
05722                 * test above to bring the voice path up.
05723                 */
05724                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05725             }
05726             sig_pri_unlock_private(pri->pvts[chanpos]);
05727             break;
05728          case PRI_EVENT_FACILITY:
05729             if (!e->facility.call || sig_pri_is_cis_call(e->facility.channel)) {
05730                /* Event came in on the dummy channel or a CIS call. */
05731 #if defined(HAVE_PRI_CALL_REROUTING)
05732                sig_pri_handle_cis_subcmds(pri, e->e, e->facility.subcmds,
05733                   e->facility.subcall);
05734 #else
05735                sig_pri_handle_cis_subcmds(pri, e->e, e->facility.subcmds,
05736                   e->facility.call);
05737 #endif   /* !defined(HAVE_PRI_CALL_REROUTING) */
05738                break;
05739             }
05740             chanpos = pri_find_principle_by_call(pri, e->facility.call);
05741             if (chanpos < 0) {
05742                ast_log(LOG_WARNING, "Span %d: Received facility for unknown call.\n",
05743                   pri->span);
05744                break;
05745             }
05746             sig_pri_lock_private(pri->pvts[chanpos]);
05747 #if defined(HAVE_PRI_CALL_REROUTING)
05748             sig_pri_handle_subcmds(pri, chanpos, e->e, e->facility.channel,
05749                e->facility.subcmds, e->facility.subcall);
05750 #else
05751             sig_pri_handle_subcmds(pri, chanpos, e->e, e->facility.channel,
05752                e->facility.subcmds, e->facility.call);
05753 #endif   /* !defined(HAVE_PRI_CALL_REROUTING) */
05754             sig_pri_unlock_private(pri->pvts[chanpos]);
05755             break;
05756          case PRI_EVENT_ANSWER:
05757             if (sig_pri_is_cis_call(e->answer.channel)) {
05758 #if defined(HAVE_PRI_CALL_WAITING)
05759                /* Call is CIS so do normal CONNECT_ACKNOWLEDGE. */
05760                pri_connect_ack(pri->pri, e->answer.call, 0);
05761 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05762                sig_pri_handle_cis_subcmds(pri, e->e, e->answer.subcmds,
05763                   e->answer.call);
05764                break;
05765             }
05766             chanpos = pri_find_fixup_principle(pri, e->answer.channel, e->answer.call);
05767             if (chanpos < 0) {
05768                break;
05769             }
05770 #if defined(HAVE_PRI_CALL_WAITING)
05771             if (pri->pvts[chanpos]->is_call_waiting) {
05772                if (pri->pvts[chanpos]->no_b_channel) {
05773                   int new_chanpos;
05774 
05775                   /*
05776                    * Need to find a free channel now or
05777                    * kill the call with PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION.
05778                    */
05779                   new_chanpos = pri_find_empty_chan(pri, 1);
05780                   if (0 <= new_chanpos) {
05781                      new_chanpos = pri_fixup_principle(pri, new_chanpos,
05782                         e->answer.call);
05783                   }
05784                   if (new_chanpos < 0) {
05785                      /*
05786                       * Either no channel was available or someone stole
05787                       * the channel!
05788                       */
05789                      ast_verb(3,
05790                         "Span %d: Channel not available for call waiting call.\n",
05791                         pri->span);
05792                      sig_pri_lock_private(pri->pvts[chanpos]);
05793                      sig_pri_handle_subcmds(pri, chanpos, e->e, e->answer.channel,
05794                         e->answer.subcmds, e->answer.call);
05795                      sig_pri_cc_generic_check(pri, chanpos, AST_CC_CCBS);
05796                      sig_pri_lock_owner(pri, chanpos);
05797                      if (pri->pvts[chanpos]->owner) {
05798                         pri->pvts[chanpos]->owner->hangupcause = PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION;
05799                         switch (pri->pvts[chanpos]->owner->_state) {
05800                         case AST_STATE_BUSY:
05801                         case AST_STATE_UP:
05802                            ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
05803                            break;
05804                         default:
05805                            pri_queue_control(pri, chanpos, AST_CONTROL_CONGESTION);
05806                            break;
05807                         }
05808                         ast_channel_unlock(pri->pvts[chanpos]->owner);
05809                      } else {
05810                         pri->pvts[chanpos]->is_call_waiting = 0;
05811                         ast_atomic_fetchadd_int(&pri->num_call_waiting_calls, -1);
05812                         pri_hangup(pri->pri, e->answer.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
05813                         pri->pvts[chanpos]->call = NULL;
05814                      }
05815                      sig_pri_unlock_private(pri->pvts[chanpos]);
05816                      sig_pri_span_devstate_changed(pri);
05817                      break;
05818                   }
05819                   chanpos = new_chanpos;
05820                }
05821                pri_connect_ack(pri->pri, e->answer.call, PVT_TO_CHANNEL(pri->pvts[chanpos]));
05822                sig_pri_span_devstate_changed(pri);
05823             } else {
05824                /* Call is normal so do normal CONNECT_ACKNOWLEDGE. */
05825                pri_connect_ack(pri->pri, e->answer.call, 0);
05826             }
05827 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05828             sig_pri_lock_private(pri->pvts[chanpos]);
05829 
05830 #if defined(HAVE_PRI_CALL_WAITING)
05831             if (pri->pvts[chanpos]->is_call_waiting) {
05832                pri->pvts[chanpos]->is_call_waiting = 0;
05833                ast_atomic_fetchadd_int(&pri->num_call_waiting_calls, -1);
05834             }
05835 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05836             sig_pri_handle_subcmds(pri, chanpos, e->e, e->answer.channel,
05837                e->answer.subcmds, e->answer.call);
05838             if (!ast_strlen_zero(pri->pvts[chanpos]->deferred_digits)) {
05839                /* We have some 'w' deferred digits to dial now. */
05840                ast_verb(3,
05841                   "Span %d: Channel %d/%d dialing deferred digit string: %s\n",
05842                   pri->span, pri->pvts[chanpos]->logicalspan,
05843                   pri->pvts[chanpos]->prioffset,
05844                   pri->pvts[chanpos]->deferred_digits);
05845                if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_DEFER_DIAL) {
05846                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_DEFER_DIAL;
05847                }
05848                sig_pri_dial_digits(pri->pvts[chanpos],
05849                   pri->pvts[chanpos]->deferred_digits);
05850             } else {
05851                if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_CONNECT) {
05852                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_CONNECT;
05853                }
05854                sig_pri_open_media(pri->pvts[chanpos]);
05855                pri_queue_control(pri, chanpos, AST_CONTROL_ANSWER);
05856                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05857                /* Enable echo cancellation if it's not on already */
05858                sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
05859             }
05860 
05861 #ifdef SUPPORT_USERUSER
05862             if (!ast_strlen_zero(e->answer.useruserinfo)) {
05863                struct ast_channel *owner;
05864 
05865                sig_pri_lock_owner(pri, chanpos);
05866                owner = pri->pvts[chanpos]->owner;
05867                if (owner) {
05868                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
05869                      e->answer.useruserinfo);
05870                   ast_channel_unlock(owner);
05871                }
05872             }
05873 #endif
05874 
05875             sig_pri_unlock_private(pri->pvts[chanpos]);
05876             break;
05877 #if defined(HAVE_PRI_CALL_WAITING)
05878          case PRI_EVENT_CONNECT_ACK:
05879             if (sig_pri_is_cis_call(e->connect_ack.channel)) {
05880                sig_pri_handle_cis_subcmds(pri, e->e, e->connect_ack.subcmds,
05881                   e->connect_ack.call);
05882                break;
05883             }
05884             chanpos = pri_find_fixup_principle(pri, e->connect_ack.channel,
05885                e->connect_ack.call);
05886             if (chanpos < 0) {
05887                break;
05888             }
05889 
05890             sig_pri_lock_private(pri->pvts[chanpos]);
05891             sig_pri_handle_subcmds(pri, chanpos, e->e, e->connect_ack.channel,
05892                e->connect_ack.subcmds, e->connect_ack.call);
05893             sig_pri_open_media(pri->pvts[chanpos]);
05894             sig_pri_unlock_private(pri->pvts[chanpos]);
05895             sig_pri_span_devstate_changed(pri);
05896             break;
05897 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05898          case PRI_EVENT_HANGUP:
05899             if (sig_pri_is_cis_call(e->hangup.channel)) {
05900                sig_pri_handle_cis_subcmds(pri, e->e, e->hangup.subcmds,
05901                   e->hangup.call);
05902                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
05903                break;
05904             }
05905             chanpos = pri_find_principle_by_call(pri, e->hangup.call);
05906             if (chanpos < 0) {
05907                /*
05908                 * Continue hanging up the call even though
05909                 * we do not remember it (if we ever did).
05910                 */
05911                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
05912                break;
05913             }
05914             sig_pri_lock_private(pri->pvts[chanpos]);
05915             sig_pri_handle_subcmds(pri, chanpos, e->e, e->hangup.channel,
05916                e->hangup.subcmds, e->hangup.call);
05917             switch (e->hangup.cause) {
05918             case PRI_CAUSE_INVALID_CALL_REFERENCE:
05919                /*
05920                 * The peer denies the existence of this call so we must
05921                 * continue hanging it up and forget about it.
05922                 */
05923                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
05924                pri->pvts[chanpos]->call = NULL;
05925                break;
05926             default:
05927                break;
05928             }
05929             if (!pri->pvts[chanpos]->alreadyhungup) {
05930                /* we're calling here dahdi_hangup so once we get there we need to clear p->call after calling pri_hangup */
05931                pri->pvts[chanpos]->alreadyhungup = 1;
05932                switch (e->hangup.cause) {
05933                case PRI_CAUSE_USER_BUSY:
05934                case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
05935                   sig_pri_cc_generic_check(pri, chanpos, AST_CC_CCBS);
05936                   break;
05937                default:
05938                   break;
05939                }
05940                if (pri->pvts[chanpos]->owner) {
05941                   int do_hangup = 0;
05942 
05943                   /* Queue a BUSY instead of a hangup if our cause is appropriate */
05944                   pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
05945                   switch (pri->pvts[chanpos]->owner->_state) {
05946                   case AST_STATE_BUSY:
05947                   case AST_STATE_UP:
05948                      do_hangup = 1;
05949                      break;
05950                   default:
05951                      if (!pri->pvts[chanpos]->outgoing) {
05952                         /*
05953                          * The incoming call leg hung up before getting
05954                          * connected so just hangup the call.
05955                          */
05956                         do_hangup = 1;
05957                         break;
05958                      }
05959                      switch (e->hangup.cause) {
05960                      case PRI_CAUSE_USER_BUSY:
05961                         pri_queue_control(pri, chanpos, AST_CONTROL_BUSY);
05962                         break;
05963                      case PRI_CAUSE_CALL_REJECTED:
05964                      case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
05965                      case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
05966                      case PRI_CAUSE_SWITCH_CONGESTION:
05967                      case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
05968                      case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
05969                         pri_queue_control(pri, chanpos, AST_CONTROL_CONGESTION);
05970                         break;
05971                      default:
05972                         do_hangup = 1;
05973                         break;
05974                      }
05975                      break;
05976                   }
05977 
05978                   if (do_hangup) {
05979 #if defined(HAVE_PRI_AOC_EVENTS)
05980                      if (detect_aoc_e_subcmd(e->hangup.subcmds)) {
05981                         /* If a AOC-E msg was sent during the release, we must use a
05982                          * AST_CONTROL_HANGUP frame to guarantee that frame gets read before hangup */
05983                         pri_queue_control(pri, chanpos, AST_CONTROL_HANGUP);
05984                      } else {
05985                         pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05986                      }
05987 #else
05988                      pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05989 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
05990                   }
05991                } else {
05992                   /*
05993                    * Continue hanging up the call even though
05994                    * we do not have an owner.
05995                    */
05996                   pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
05997                   pri->pvts[chanpos]->call = NULL;
05998                }
05999                ast_verb(3, "Span %d: Channel %d/%d got hangup, cause %d\n",
06000                   pri->span, pri->pvts[chanpos]->logicalspan,
06001                   pri->pvts[chanpos]->prioffset, e->hangup.cause);
06002             } else {
06003                /* Continue hanging up the call. */
06004                pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
06005                pri->pvts[chanpos]->call = NULL;
06006             }
06007 #if defined(FORCE_RESTART_UNAVAIL_CHANS)
06008             if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL
06009                && pri->sig != SIG_BRI_PTMP && !pri->resetting
06010                && pri->pvts[chanpos]->resetting == SIG_PRI_RESET_IDLE) {
06011                ast_verb(3,
06012                   "Span %d: Forcing restart of channel %d/%d since channel reported in use\n",
06013                   pri->span, pri->pvts[chanpos]->logicalspan,
06014                   pri->pvts[chanpos]->prioffset);
06015                pri->pvts[chanpos]->resetting = SIG_PRI_RESET_ACTIVE;
06016                pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
06017             }
06018 #endif   /* defined(FORCE_RESTART_UNAVAIL_CHANS) */
06019             if (e->hangup.aoc_units > -1)
06020                ast_verb(3, "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
06021                   pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
06022 
06023 #ifdef SUPPORT_USERUSER
06024             if (!ast_strlen_zero(e->hangup.useruserinfo)) {
06025                struct ast_channel *owner;
06026 
06027                sig_pri_lock_owner(pri, chanpos);
06028                owner = pri->pvts[chanpos]->owner;
06029                if (owner) {
06030                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
06031                      e->hangup.useruserinfo);
06032                   ast_channel_unlock(owner);
06033                }
06034             }
06035 #endif
06036 
06037             sig_pri_unlock_private(pri->pvts[chanpos]);
06038             sig_pri_span_devstate_changed(pri);
06039             break;
06040          case PRI_EVENT_HANGUP_REQ:
06041             if (sig_pri_is_cis_call(e->hangup.channel)) {
06042                sig_pri_handle_cis_subcmds(pri, e->e, e->hangup.subcmds,
06043                   e->hangup.call);
06044                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
06045                break;
06046             }
06047             chanpos = pri_find_principle_by_call(pri, e->hangup.call);
06048             if (chanpos < 0) {
06049                /*
06050                 * Continue hanging up the call even though
06051                 * we do not remember it (if we ever did).
06052                 */
06053                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
06054                break;
06055             }
06056             sig_pri_lock_private(pri->pvts[chanpos]);
06057             sig_pri_handle_subcmds(pri, chanpos, e->e, e->hangup.channel,
06058                e->hangup.subcmds, e->hangup.call);
06059 #if defined(HAVE_PRI_CALL_HOLD)
06060             if (e->hangup.call_active && e->hangup.call_held
06061                && pri->hold_disconnect_transfer) {
06062                /* We are to transfer the call instead of simply hanging up. */
06063                sig_pri_unlock_private(pri->pvts[chanpos]);
06064                if (!sig_pri_attempt_transfer(pri, e->hangup.call_held, 1,
06065                   e->hangup.call_active, 0, NULL, NULL)) {
06066                   break;
06067                }
06068                sig_pri_lock_private(pri->pvts[chanpos]);
06069             }
06070 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06071             switch (e->hangup.cause) {
06072             case PRI_CAUSE_USER_BUSY:
06073             case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
06074                sig_pri_cc_generic_check(pri, chanpos, AST_CC_CCBS);
06075                break;
06076             case PRI_CAUSE_INVALID_CALL_REFERENCE:
06077                /*
06078                 * The peer denies the existence of this call so we must
06079                 * continue hanging it up and forget about it.  We should not
06080                 * get this cause here, but for completeness we will handle it
06081                 * anyway.
06082                 */
06083                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
06084                pri->pvts[chanpos]->call = NULL;
06085                break;
06086             default:
06087                break;
06088             }
06089             if (pri->pvts[chanpos]->owner) {
06090                int do_hangup = 0;
06091 
06092                pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
06093                switch (pri->pvts[chanpos]->owner->_state) {
06094                case AST_STATE_BUSY:
06095                case AST_STATE_UP:
06096                   do_hangup = 1;
06097                   break;
06098                default:
06099                   if (!pri->pvts[chanpos]->outgoing) {
06100                      /*
06101                       * The incoming call leg hung up before getting
06102                       * connected so just hangup the call.
06103                       */
06104                      do_hangup = 1;
06105                      break;
06106                   }
06107                   switch (e->hangup.cause) {
06108                   case PRI_CAUSE_USER_BUSY:
06109                      pri_queue_control(pri, chanpos, AST_CONTROL_BUSY);
06110                      break;
06111                   case PRI_CAUSE_CALL_REJECTED:
06112                   case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
06113                   case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
06114                   case PRI_CAUSE_SWITCH_CONGESTION:
06115                   case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
06116                   case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
06117                      pri_queue_control(pri, chanpos, AST_CONTROL_CONGESTION);
06118                      break;
06119                   default:
06120                      do_hangup = 1;
06121                      break;
06122                   }
06123                   break;
06124                }
06125 
06126                if (do_hangup) {
06127 #if defined(HAVE_PRI_AOC_EVENTS)
06128                   if (!pri->pvts[chanpos]->holding_aoce
06129                      && pri->aoce_delayhangup
06130                      && ast_bridged_channel(pri->pvts[chanpos]->owner)) {
06131                      sig_pri_send_aoce_termination_request(pri, chanpos,
06132                         pri_get_timer(pri->pri, PRI_TIMER_T305) / 2);
06133                   } else if (detect_aoc_e_subcmd(e->hangup.subcmds)) {
06134                      /* If a AOC-E msg was sent during the Disconnect, we must use a AST_CONTROL_HANGUP frame
06135                       * to guarantee that frame gets read before hangup */
06136                      pri_queue_control(pri, chanpos, AST_CONTROL_HANGUP);
06137                   } else {
06138                      pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06139                   }
06140 #else
06141                   pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06142 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
06143                }
06144                ast_verb(3, "Span %d: Channel %d/%d got hangup request, cause %d\n",
06145                   pri->span, pri->pvts[chanpos]->logicalspan,
06146                   pri->pvts[chanpos]->prioffset, e->hangup.cause);
06147             } else {
06148                /*
06149                 * Continue hanging up the call even though
06150                 * we do not have an owner.
06151                 */
06152                pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
06153                pri->pvts[chanpos]->call = NULL;
06154             }
06155 #if defined(FORCE_RESTART_UNAVAIL_CHANS)
06156             if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL
06157                && pri->sig != SIG_BRI_PTMP && !pri->resetting
06158                && pri->pvts[chanpos]->resetting == SIG_PRI_RESET_IDLE) {
06159                ast_verb(3,
06160                   "Span %d: Forcing restart of channel %d/%d since channel reported in use\n",
06161                   pri->span, pri->pvts[chanpos]->logicalspan,
06162                   pri->pvts[chanpos]->prioffset);
06163                pri->pvts[chanpos]->resetting = SIG_PRI_RESET_ACTIVE;
06164                pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
06165             }
06166 #endif   /* defined(FORCE_RESTART_UNAVAIL_CHANS) */
06167 
06168 #ifdef SUPPORT_USERUSER
06169             if (!ast_strlen_zero(e->hangup.useruserinfo)) {
06170                struct ast_channel *owner;
06171 
06172                sig_pri_lock_owner(pri, chanpos);
06173                owner = pri->pvts[chanpos]->owner;
06174                if (owner) {
06175                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
06176                      e->hangup.useruserinfo);
06177                   ast_channel_unlock(owner);
06178                }
06179             }
06180 #endif
06181 
06182             sig_pri_unlock_private(pri->pvts[chanpos]);
06183             sig_pri_span_devstate_changed(pri);
06184             break;
06185          case PRI_EVENT_HANGUP_ACK:
06186             if (sig_pri_is_cis_call(e->hangup.channel)) {
06187                sig_pri_handle_cis_subcmds(pri, e->e, e->hangup.subcmds,
06188                   e->hangup.call);
06189                break;
06190             }
06191             chanpos = pri_find_principle_by_call(pri, e->hangup.call);
06192             if (chanpos < 0) {
06193                break;
06194             }
06195             sig_pri_lock_private(pri->pvts[chanpos]);
06196             pri->pvts[chanpos]->call = NULL;
06197             if (pri->pvts[chanpos]->owner) {
06198                ast_verb(3, "Span %d: Channel %d/%d got hangup ACK\n", pri->span,
06199                   pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset);
06200             }
06201 #ifdef SUPPORT_USERUSER
06202             if (!ast_strlen_zero(e->hangup.useruserinfo)) {
06203                struct ast_channel *owner;
06204 
06205                sig_pri_lock_owner(pri, chanpos);
06206                owner = pri->pvts[chanpos]->owner;
06207                if (owner) {
06208                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
06209                      e->hangup.useruserinfo);
06210                   ast_channel_unlock(owner);
06211                }
06212             }
06213 #endif
06214             sig_pri_unlock_private(pri->pvts[chanpos]);
06215             sig_pri_span_devstate_changed(pri);
06216             break;
06217          case PRI_EVENT_CONFIG_ERR:
06218             ast_log(LOG_WARNING, "PRI Error on span %d: %s\n", pri->span, e->err.err);
06219             break;
06220          case PRI_EVENT_RESTART_ACK:
06221             chanpos = pri_find_principle(pri, e->restartack.channel, NULL);
06222             if (chanpos < 0) {
06223                /* Sometime switches (e.g. I421 / British Telecom) don't give us the
06224                   channel number, so we have to figure it out...  This must be why
06225                   everybody resets exactly a channel at a time. */
06226                for (x = 0; x < pri->numchans; x++) {
06227                   if (pri->pvts[x]
06228                      && pri->pvts[x]->resetting != SIG_PRI_RESET_IDLE) {
06229                      chanpos = x;
06230                      sig_pri_lock_private(pri->pvts[chanpos]);
06231                      ast_debug(1,
06232                         "Span %d: Assuming restart ack is for channel %d/%d\n",
06233                         pri->span, pri->pvts[chanpos]->logicalspan,
06234                         pri->pvts[chanpos]->prioffset);
06235                      if (pri->pvts[chanpos]->owner) {
06236                         ast_log(LOG_WARNING,
06237                            "Span %d: Got restart ack on channel %d/%d with owner\n",
06238                            pri->span, pri->pvts[chanpos]->logicalspan,
06239                            pri->pvts[chanpos]->prioffset);
06240                         pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06241                      }
06242                      pri->pvts[chanpos]->resetting = SIG_PRI_RESET_IDLE;
06243                      ast_verb(3,
06244                         "Span %d: Channel %d/%d successfully restarted\n",
06245                         pri->span, pri->pvts[chanpos]->logicalspan,
06246                         pri->pvts[chanpos]->prioffset);
06247                      sig_pri_unlock_private(pri->pvts[chanpos]);
06248                      if (pri->resetting)
06249                         pri_check_restart(pri);
06250                      break;
06251                   }
06252                }
06253                if (chanpos < 0) {
06254                   ast_log(LOG_WARNING,
06255                      "Span %d: Restart ACK on strange channel %d/%d\n",
06256                      pri->span, PRI_SPAN(e->restartack.channel),
06257                      PRI_CHANNEL(e->restartack.channel));
06258                }
06259             } else {
06260                sig_pri_lock_private(pri->pvts[chanpos]);
06261                if (pri->pvts[chanpos]->resetting == SIG_PRI_RESET_IDLE) {
06262                   /* The channel is not in the resetting state. */
06263                   ast_debug(1,
06264                      "Span %d: Unexpected or late restart ack on channel %d/%d (Ignoring)\n",
06265                      pri->span, pri->pvts[chanpos]->logicalspan,
06266                      pri->pvts[chanpos]->prioffset);
06267                   sig_pri_unlock_private(pri->pvts[chanpos]);
06268                   break;
06269                }
06270                if (pri->pvts[chanpos]->owner) {
06271                   ast_log(LOG_WARNING,
06272                      "Span %d: Got restart ack on channel %d/%d with owner\n",
06273                      pri->span, pri->pvts[chanpos]->logicalspan,
06274                      pri->pvts[chanpos]->prioffset);
06275                   pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06276                }
06277                pri->pvts[chanpos]->resetting = SIG_PRI_RESET_IDLE;
06278                ast_verb(3,
06279                   "Span %d: Channel %d/%d successfully restarted\n",
06280                   pri->span, pri->pvts[chanpos]->logicalspan,
06281                   pri->pvts[chanpos]->prioffset);
06282                sig_pri_unlock_private(pri->pvts[chanpos]);
06283                if (pri->resetting)
06284                   pri_check_restart(pri);
06285             }
06286             break;
06287          case PRI_EVENT_SETUP_ACK:
06288             if (sig_pri_is_cis_call(e->setup_ack.channel)) {
06289                sig_pri_handle_cis_subcmds(pri, e->e, e->setup_ack.subcmds,
06290                   e->setup_ack.call);
06291                break;
06292             }
06293             chanpos = pri_find_fixup_principle(pri, e->setup_ack.channel,
06294                e->setup_ack.call);
06295             if (chanpos < 0) {
06296                break;
06297             }
06298             sig_pri_lock_private(pri->pvts[chanpos]);
06299             sig_pri_handle_subcmds(pri, chanpos, e->e, e->setup_ack.channel,
06300                e->setup_ack.subcmds, e->setup_ack.call);
06301             if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_OVERLAP) {
06302                pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_OVERLAP;
06303             }
06304 
06305             /* Send any queued digits */
06306             len = strlen(pri->pvts[chanpos]->dialdest);
06307             for (x = 0; x < len; ++x) {
06308                ast_debug(1, "Sending pending digit '%c'\n", pri->pvts[chanpos]->dialdest[x]);
06309                pri_information(pri->pri, pri->pvts[chanpos]->call,
06310                   pri->pvts[chanpos]->dialdest[x]);
06311             }
06312 
06313             if (!pri->pvts[chanpos]->progress
06314                && (pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING)
06315                && !pri->pvts[chanpos]->digital
06316                && !pri->pvts[chanpos]->no_b_channel
06317 #if defined(HAVE_PRI_SETUP_ACK_INBAND)
06318                /*
06319                 * We only care about PRI_PROG_INBAND_AVAILABLE to open the
06320                 * voice path.
06321                 *
06322                 * We explicitly DO NOT want to check PRI_PROG_CALL_NOT_E2E_ISDN
06323                 * because it will mess up ISDN to SIP interoperability for
06324                 * the ALERTING message.
06325                 *
06326                 * Q.931 Section 5.1.3 says that in scenarios with overlap
06327                 * dialing where no called digits are received and the tone
06328                 * option requires dialtone, the switch MAY send an inband
06329                 * progress indication ie to indicate dialtone presence in
06330                 * the SETUP ACKNOWLEDGE.  Therefore, if we did not send any
06331                 * digits with the SETUP then we must assume that dialtone
06332                 * is present and open the voice path.  Fortunately when
06333                 * interoperating with SIP, we should be sending digits.
06334                 */
06335                && ((e->setup_ack.progressmask & PRI_PROG_INBAND_AVAILABLE)
06336                   || pri->inband_on_setup_ack
06337                   || pri->pvts[chanpos]->no_dialed_digits)
06338 #endif   /* defined(HAVE_PRI_SETUP_ACK_INBAND) */
06339                ) {
06340                /*
06341                 * Call has a channel.
06342                 * Indicate for overlap dialing that dialtone may be present.
06343                 */
06344                pri_queue_control(pri, chanpos, AST_CONTROL_PROGRESS);
06345                pri->pvts[chanpos]->progress = 1;/* Claim to have seen inband-information */
06346                sig_pri_set_dialing(pri->pvts[chanpos], 0);
06347                sig_pri_open_media(pri->pvts[chanpos]);
06348             }
06349             sig_pri_unlock_private(pri->pvts[chanpos]);
06350             break;
06351          case PRI_EVENT_NOTIFY:
06352             if (sig_pri_is_cis_call(e->notify.channel)) {
06353 #if defined(HAVE_PRI_CALL_HOLD)
06354                sig_pri_handle_cis_subcmds(pri, e->e, e->notify.subcmds,
06355                   e->notify.call);
06356 #else
06357                sig_pri_handle_cis_subcmds(pri, e->e, e->notify.subcmds, NULL);
06358 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
06359                break;
06360             }
06361 #if defined(HAVE_PRI_CALL_HOLD)
06362             chanpos = pri_find_principle_by_call(pri, e->notify.call);
06363             if (chanpos < 0) {
06364                ast_log(LOG_WARNING, "Span %d: Received NOTIFY for unknown call.\n",
06365                   pri->span);
06366                break;
06367             }
06368 #else
06369             /*
06370              * This version of libpri does not supply a call pointer for
06371              * this message.  We are just going to have to trust that the
06372              * correct principle is found.
06373              */
06374             chanpos = pri_find_principle(pri, e->notify.channel, NULL);
06375             if (chanpos < 0) {
06376                ast_log(LOG_WARNING, "Received NOTIFY on unconfigured channel %d/%d span %d\n",
06377                   PRI_SPAN(e->notify.channel), PRI_CHANNEL(e->notify.channel), pri->span);
06378                break;
06379             }
06380 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
06381             sig_pri_lock_private(pri->pvts[chanpos]);
06382 #if defined(HAVE_PRI_CALL_HOLD)
06383             sig_pri_handle_subcmds(pri, chanpos, e->e, e->notify.channel,
06384                e->notify.subcmds, e->notify.call);
06385 #else
06386             sig_pri_handle_subcmds(pri, chanpos, e->e, e->notify.channel,
06387                e->notify.subcmds, NULL);
06388 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
06389             switch (e->notify.info) {
06390             case PRI_NOTIFY_REMOTE_HOLD:
06391                if (!pri->discardremoteholdretrieval) {
06392                   pri_queue_control(pri, chanpos, AST_CONTROL_HOLD);
06393                }
06394                break;
06395             case PRI_NOTIFY_REMOTE_RETRIEVAL:
06396                if (!pri->discardremoteholdretrieval) {
06397                   pri_queue_control(pri, chanpos, AST_CONTROL_UNHOLD);
06398                }
06399                break;
06400             }
06401             sig_pri_unlock_private(pri->pvts[chanpos]);
06402             break;
06403 #if defined(HAVE_PRI_CALL_HOLD)
06404          case PRI_EVENT_HOLD:
06405             /* We should not be getting any CIS calls with this message type. */
06406             if (sig_pri_handle_hold(pri, e)) {
06407                pri_hold_rej(pri->pri, e->hold.call,
06408                   PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED);
06409             } else {
06410                pri_hold_ack(pri->pri, e->hold.call);
06411             }
06412             break;
06413 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06414 #if defined(HAVE_PRI_CALL_HOLD)
06415          case PRI_EVENT_HOLD_ACK:
06416             ast_debug(1, "Event: HOLD_ACK\n");
06417             break;
06418 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06419 #if defined(HAVE_PRI_CALL_HOLD)
06420          case PRI_EVENT_HOLD_REJ:
06421             ast_debug(1, "Event: HOLD_REJ\n");
06422             break;
06423 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06424 #if defined(HAVE_PRI_CALL_HOLD)
06425          case PRI_EVENT_RETRIEVE:
06426             /* We should not be getting any CIS calls with this message type. */
06427             sig_pri_handle_retrieve(pri, e);
06428             break;
06429 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06430 #if defined(HAVE_PRI_CALL_HOLD)
06431          case PRI_EVENT_RETRIEVE_ACK:
06432             ast_debug(1, "Event: RETRIEVE_ACK\n");
06433             break;
06434 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06435 #if defined(HAVE_PRI_CALL_HOLD)
06436          case PRI_EVENT_RETRIEVE_REJ:
06437             ast_debug(1, "Event: RETRIEVE_REJ\n");
06438             break;
06439 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06440          default:
06441             ast_debug(1, "Event: %d\n", e->e);
06442             break;
06443          }
06444       }
06445       ast_mutex_unlock(&pri->lock);
06446    }
06447    /* Never reached */
06448    return NULL;
06449 }
06450 
06451 void sig_pri_init_pri(struct sig_pri_span *pri)
06452 {
06453    int i;
06454 
06455    memset(pri, 0, sizeof(*pri));
06456 
06457    ast_mutex_init(&pri->lock);
06458 
06459    pri->master = AST_PTHREADT_NULL;
06460    for (i = 0; i < SIG_PRI_NUM_DCHANS; i++)
06461       pri->fds[i] = -1;
06462 }
06463 
06464 int sig_pri_hangup(struct sig_pri_chan *p, struct ast_channel *ast)
06465 {
06466    ast_debug(1, "%s %d\n", __FUNCTION__, p->channel);
06467    if (!ast->tech_pvt) {
06468       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
06469       return 0;
06470    }
06471 
06472    sig_pri_set_outgoing(p, 0);
06473    sig_pri_set_digital(p, 0); /* push up to parent for EC*/
06474 #if defined(HAVE_PRI_CALL_WAITING)
06475    if (p->is_call_waiting) {
06476       p->is_call_waiting = 0;
06477       ast_atomic_fetchadd_int(&p->pri->num_call_waiting_calls, -1);
06478    }
06479 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
06480    p->call_level = SIG_PRI_CALL_LEVEL_IDLE;
06481    p->progress = 0;
06482    p->cid_num[0] = '\0';
06483    p->cid_subaddr[0] = '\0';
06484    p->cid_name[0] = '\0';
06485    p->user_tag[0] = '\0';
06486    p->exten[0] = '\0';
06487    sig_pri_set_dialing(p, 0);
06488 
06489    /* Make sure we really have a call */
06490    pri_grab(p, p->pri);
06491    if (p->call) {
06492 #if defined(SUPPORT_USERUSER)
06493       const char *useruser = pbx_builtin_getvar_helper(ast, "USERUSERINFO");
06494 
06495       if (!ast_strlen_zero(useruser)) {
06496          pri_call_set_useruser(p->call, useruser);
06497       }
06498 #endif   /* defined(SUPPORT_USERUSER) */
06499 
06500 #if defined(HAVE_PRI_AOC_EVENTS)
06501       if (p->holding_aoce) {
06502          pri_aoc_e_send(p->pri->pri, p->call, &p->aoc_e);
06503       }
06504 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
06505 
06506       if (p->alreadyhungup) {
06507          ast_debug(1, "Already hungup...  Calling hangup once, and clearing call\n");
06508 
06509          pri_hangup(p->pri->pri, p->call, -1);
06510          p->call = NULL;
06511       } else {
06512          const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
06513          int icause = ast->hangupcause ? ast->hangupcause : -1;
06514 
06515          p->alreadyhungup = 1;
06516          if (!ast_strlen_zero(cause)) {
06517             if (atoi(cause)) {
06518                icause = atoi(cause);
06519             }
06520          }
06521          ast_debug(1,
06522             "Not yet hungup...  Calling hangup with cause %d, and clearing call\n",
06523             icause);
06524 
06525          pri_hangup(p->pri->pri, p->call, icause);
06526       }
06527    }
06528 #if defined(HAVE_PRI_AOC_EVENTS)
06529    p->aoc_s_request_invoke_id_valid = 0;
06530    p->holding_aoce = 0;
06531    p->waiting_for_aoce = 0;
06532 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
06533 
06534    p->allocated = 0;
06535    p->owner = NULL;
06536 
06537    sig_pri_span_devstate_changed(p->pri);
06538    pri_rel(p->pri);
06539    return 0;
06540 }
06541 
06542 /*!
06543  * \brief Extract the called number and subaddress from the dial string.
06544  * \since 1.8
06545  *
06546  * \param p sig_pri channel structure.
06547  * \param rdest Dial string buffer to extract called number and subaddress.
06548  * \param called Buffer to fill with extracted <number>[:<subaddress>]
06549  * \param called_buff_size Size of buffer to fill.
06550  *
06551  * \note Parsing must remain in sync with sig_pri_call().
06552  *
06553  * \return Nothing
06554  */
06555 void sig_pri_extract_called_num_subaddr(struct sig_pri_chan *p, const char *rdest, char *called, size_t called_buff_size)
06556 {
06557    char *dial;
06558    char *number;
06559    char *subaddr;
06560    AST_DECLARE_APP_ARGS(args,
06561       AST_APP_ARG(group);  /* channel/group token */
06562       AST_APP_ARG(ext); /* extension token */
06563       //AST_APP_ARG(opts); /* options token */
06564       AST_APP_ARG(other);  /* Any remining unused arguments */
06565    );
06566 
06567    /* Get private copy of dial string and break it up. */
06568    dial = ast_strdupa(rdest);
06569    AST_NONSTANDARD_APP_ARGS(args, dial, '/');
06570 
06571    number = args.ext;
06572    if (!number) {
06573       number = "";
06574    }
06575 
06576    /* Find and extract dialed_subaddress */
06577    subaddr = strchr(number, ':');
06578    if (subaddr) {
06579       *subaddr++ = '\0';
06580 
06581       /* Skip subaddress type prefix. */
06582       switch (*subaddr) {
06583       case 'U':
06584       case 'u':
06585       case 'N':
06586       case 'n':
06587          ++subaddr;
06588          break;
06589       default:
06590          break;
06591       }
06592    }
06593 
06594    /* Skip type-of-number/dial-plan prefix characters. */
06595    if (strlen(number) < p->stripmsd) {
06596       number = "";
06597    } else {
06598       char *deferred;
06599 
06600       number += p->stripmsd;
06601       deferred = strchr(number, 'w');
06602       if (deferred) {
06603          /* Remove any 'w' deferred digits. */
06604          *deferred = '\0';
06605       }
06606       while (isalpha(*number)) {
06607          ++number;
06608       }
06609    }
06610 
06611    /* Fill buffer with extracted number and subaddress. */
06612    if (ast_strlen_zero(subaddr)) {
06613       /* Put in called number only since there is no subaddress. */
06614       snprintf(called, called_buff_size, "%s", number);
06615    } else {
06616       /* Put in called number and subaddress. */
06617       snprintf(called, called_buff_size, "%s:%s", number, subaddr);
06618    }
06619 }
06620 
06621 enum SIG_PRI_CALL_OPT_FLAGS {
06622    OPT_KEYPAD =         (1 << 0),
06623    OPT_REVERSE_CHARGE = (1 << 1),   /* Collect call */
06624    OPT_AOC_REQUEST =    (1 << 2),   /* AOC Request */
06625 };
06626 enum SIG_PRI_CALL_OPT_ARGS {
06627    OPT_ARG_KEYPAD = 0,
06628    OPT_ARG_AOC_REQUEST,
06629 
06630    /* note: this entry _MUST_ be the last one in the enum */
06631    OPT_ARG_ARRAY_SIZE,
06632 };
06633 
06634 AST_APP_OPTIONS(sig_pri_call_opts, BEGIN_OPTIONS
06635    AST_APP_OPTION_ARG('K', OPT_KEYPAD, OPT_ARG_KEYPAD),
06636    AST_APP_OPTION('R', OPT_REVERSE_CHARGE),
06637    AST_APP_OPTION_ARG('A', OPT_AOC_REQUEST, OPT_ARG_AOC_REQUEST),
06638 END_OPTIONS);
06639 
06640 /*! \note Parsing must remain in sync with sig_pri_extract_called_num_subaddr(). */
06641 int sig_pri_call(struct sig_pri_chan *p, struct ast_channel *ast, char *rdest, int timeout, int layer1)
06642 {
06643    char dest[256]; /* must be same length as p->dialdest */
06644    struct ast_party_subaddress dialed_subaddress; /* Called subaddress */
06645    struct pri_sr *sr;
06646    char *c, *l, *n, *s;
06647 #ifdef SUPPORT_USERUSER
06648    const char *useruser;
06649 #endif
06650    int core_id;
06651    int pridialplan;
06652    int dp_strip;
06653    int prilocaldialplan;
06654    int ldp_strip;
06655    int exclusive;
06656 #if defined(HAVE_PRI_SETUP_KEYPAD)
06657    const char *keypad;
06658 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
06659    AST_DECLARE_APP_ARGS(args,
06660       AST_APP_ARG(group);  /* channel/group token */
06661       AST_APP_ARG(ext); /* extension token */
06662       AST_APP_ARG(opts);   /* options token */
06663       AST_APP_ARG(other);  /* Any remining unused arguments */
06664    );
06665    struct ast_flags opts;
06666    char *opt_args[OPT_ARG_ARRAY_SIZE];
06667 
06668    ast_log(LOG_DEBUG, "CALLER NAME: %s NUM: %s\n",
06669       S_COR(ast->connected.id.name.valid, ast->connected.id.name.str, ""),
06670       S_COR(ast->connected.id.number.valid, ast->connected.id.number.str, ""));
06671 
06672    if (!p->pri) {
06673       ast_log(LOG_ERROR, "Could not find pri on channel %d\n", p->channel);
06674       return -1;
06675    }
06676 
06677    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
06678       ast_log(LOG_WARNING, "sig_pri_call called on %s, neither down nor reserved\n", ast->name);
06679       return -1;
06680    }
06681 
06682    p->dialdest[0] = '\0';
06683    sig_pri_set_outgoing(p, 1);
06684 
06685    ast_copy_string(dest, rdest, sizeof(dest));
06686    AST_NONSTANDARD_APP_ARGS(args, dest, '/');
06687    if (ast_app_parse_options(sig_pri_call_opts, &opts, opt_args, args.opts)) {
06688       /* General invalid option syntax. */
06689       return -1;
06690    }
06691 
06692    c = args.ext;
06693    if (!c) {
06694       c = "";
06695    }
06696 
06697    /* setup dialed_subaddress if found */
06698    ast_party_subaddress_init(&dialed_subaddress);
06699    s = strchr(c, ':');
06700    if (s) {
06701       *s = '\0';
06702       s++;
06703       /* prefix */
06704       /* 'n' = NSAP */
06705       /* 'u' = User Specified */
06706       /* Default = NSAP */
06707       switch (*s) {
06708       case 'U':
06709       case 'u':
06710          s++;
06711          dialed_subaddress.type = 2;
06712          break;
06713       case 'N':
06714       case 'n':
06715          s++;
06716          /* default already covered with ast_party_subaddress_init */
06717          break;
06718       }
06719       dialed_subaddress.str = s;
06720       dialed_subaddress.valid = 1;
06721    }
06722 
06723    l = NULL;
06724    n = NULL;
06725    if (!p->hidecallerid) {
06726       if (ast->connected.id.number.valid) {
06727          /* If we get to the end of this loop without breaking, there's no
06728           * calleridnum.  This is done instead of testing for "unknown" or
06729           * the thousands of other ways that the calleridnum could be
06730           * invalid. */
06731          for (l = ast->connected.id.number.str; l && *l; l++) {
06732             if (strchr("0123456789", *l)) {
06733                l = ast->connected.id.number.str;
06734                break;
06735             }
06736          }
06737       } else {
06738          l = NULL;
06739       }
06740       if (!p->hidecalleridname) {
06741          n = ast->connected.id.name.valid ? ast->connected.id.name.str : NULL;
06742       }
06743    }
06744 
06745    if (strlen(c) < p->stripmsd) {
06746       ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
06747       return -1;
06748    }
06749 
06750    /* Extract any 'w' deferred digits. */
06751    s = strchr(c + p->stripmsd, 'w');
06752    if (s) {
06753       *s++ = '\0';
06754       ast_copy_string(p->deferred_digits, s, sizeof(p->deferred_digits));
06755       /*
06756        * Since we have a 'w', this means that there will not be any
06757        * more normal dialed digits.  Therefore, the sending complete
06758        * ie needs to be sent with any normal digits.
06759        */
06760    } else {
06761       p->deferred_digits[0] = '\0';
06762    }
06763 
06764    pri_grab(p, p->pri);
06765    if (!(p->call = pri_new_call(p->pri->pri))) {
06766       ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
06767       pri_rel(p->pri);
06768       return -1;
06769    }
06770    if (!(sr = pri_sr_new())) {
06771       ast_log(LOG_WARNING, "Failed to allocate setup request on channel %d\n",
06772          p->channel);
06773       pri_destroycall(p->pri->pri, p->call);
06774       p->call = NULL;
06775       pri_rel(p->pri);
06776       return -1;
06777    }
06778 
06779    sig_pri_set_digital(p, IS_DIGITAL(ast->transfercapability));   /* push up to parent for EC */
06780 
06781 #if defined(HAVE_PRI_CALL_WAITING)
06782    if (p->is_call_waiting) {
06783       /*
06784        * Indicate that this is a call waiting call.
06785        * i.e., Normal call but with no B channel.
06786        */
06787       pri_sr_set_channel(sr, 0, 0, 1);
06788    } else
06789 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
06790    {
06791       /* Should the picked channel be used exclusively? */
06792       if (p->priexclusive || p->pri->nodetype == PRI_NETWORK) {
06793          exclusive = 1;
06794       } else {
06795          exclusive = 0;
06796       }
06797       pri_sr_set_channel(sr, PVT_TO_CHANNEL(p), exclusive, 1);
06798    }
06799 
06800    pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability,
06801       (p->digital ? -1 : layer1));
06802 
06803    if (p->pri->facilityenable)
06804       pri_facility_enable(p->pri->pri);
06805 
06806    ast_verb(3, "Requested transfer capability: 0x%.2x - %s\n", (unsigned)ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
06807    dp_strip = 0;
06808    pridialplan = p->pri->dialplan - 1;
06809    if (pridialplan == -2 || pridialplan == -3) { /* compute dynamically */
06810       if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
06811          if (pridialplan == -2) {
06812             dp_strip = strlen(p->pri->internationalprefix);
06813          }
06814          pridialplan = PRI_INTERNATIONAL_ISDN;
06815       } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
06816          if (pridialplan == -2) {
06817             dp_strip = strlen(p->pri->nationalprefix);
06818          }
06819          pridialplan = PRI_NATIONAL_ISDN;
06820       } else {
06821          pridialplan = PRI_LOCAL_ISDN;
06822       }
06823    }
06824    while (c[p->stripmsd] > '9' && c[p->stripmsd] != '*' && c[p->stripmsd] != '#') {
06825       switch (c[p->stripmsd]) {
06826       case 'U':
06827          pridialplan = (PRI_TON_UNKNOWN << 4) | (pridialplan & 0xf);
06828          break;
06829       case 'I':
06830          pridialplan = (PRI_TON_INTERNATIONAL << 4) | (pridialplan & 0xf);
06831          break;
06832       case 'N':
06833          pridialplan = (PRI_TON_NATIONAL << 4) | (pridialplan & 0xf);
06834          break;
06835       case 'L':
06836          pridialplan = (PRI_TON_NET_SPECIFIC << 4) | (pridialplan & 0xf);
06837          break;
06838       case 'S':
06839          pridialplan = (PRI_TON_SUBSCRIBER << 4) | (pridialplan & 0xf);
06840          break;
06841       case 'V':
06842          pridialplan = (PRI_TON_ABBREVIATED << 4) | (pridialplan & 0xf);
06843          break;
06844       case 'R':
06845          pridialplan = (PRI_TON_RESERVED << 4) | (pridialplan & 0xf);
06846          break;
06847       case 'u':
06848          pridialplan = PRI_NPI_UNKNOWN | (pridialplan & 0xf0);
06849          break;
06850       case 'e':
06851          pridialplan = PRI_NPI_E163_E164 | (pridialplan & 0xf0);
06852          break;
06853       case 'x':
06854          pridialplan = PRI_NPI_X121 | (pridialplan & 0xf0);
06855          break;
06856       case 'f':
06857          pridialplan = PRI_NPI_F69 | (pridialplan & 0xf0);
06858          break;
06859       case 'n':
06860          pridialplan = PRI_NPI_NATIONAL | (pridialplan & 0xf0);
06861          break;
06862       case 'p':
06863          pridialplan = PRI_NPI_PRIVATE | (pridialplan & 0xf0);
06864          break;
06865       case 'r':
06866          pridialplan = PRI_NPI_RESERVED | (pridialplan & 0xf0);
06867          break;
06868       default:
06869          if (isalpha(c[p->stripmsd])) {
06870             ast_log(LOG_WARNING, "Unrecognized pridialplan %s modifier: %c\n",
06871                c[p->stripmsd] > 'Z' ? "NPI" : "TON", c[p->stripmsd]);
06872          }
06873          break;
06874       }
06875       c++;
06876    }
06877 #if defined(HAVE_PRI_SETUP_KEYPAD)
06878    if (ast_test_flag(&opts, OPT_KEYPAD)
06879       && !ast_strlen_zero(opt_args[OPT_ARG_KEYPAD])) {
06880       /* We have a keypad facility digits option with digits. */
06881       keypad = opt_args[OPT_ARG_KEYPAD];
06882       pri_sr_set_keypad_digits(sr, keypad);
06883    } else {
06884       keypad = NULL;
06885    }
06886    if (!keypad || !ast_strlen_zero(c + p->stripmsd + dp_strip))
06887 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
06888    {
06889       char *called = c + p->stripmsd + dp_strip;
06890 
06891       pri_sr_set_called(sr, called, pridialplan, s ? 1 : 0);
06892 #if defined(HAVE_PRI_SETUP_ACK_INBAND)
06893       p->no_dialed_digits = !called[0];
06894 #endif   /* defined(HAVE_PRI_SETUP_ACK_INBAND) */
06895    }
06896 
06897 #if defined(HAVE_PRI_SUBADDR)
06898    if (dialed_subaddress.valid) {
06899       struct pri_party_subaddress subaddress;
06900 
06901       memset(&subaddress, 0, sizeof(subaddress));
06902       sig_pri_party_subaddress_from_ast(&subaddress, &dialed_subaddress);
06903       pri_sr_set_called_subaddress(sr, &subaddress);
06904    }
06905 #endif   /* defined(HAVE_PRI_SUBADDR) */
06906 #if defined(HAVE_PRI_REVERSE_CHARGE)
06907    if (ast_test_flag(&opts, OPT_REVERSE_CHARGE)) {
06908       pri_sr_set_reversecharge(sr, PRI_REVERSECHARGE_REQUESTED);
06909    }
06910 #endif   /* defined(HAVE_PRI_REVERSE_CHARGE) */
06911 #if defined(HAVE_PRI_AOC_EVENTS)
06912    if (ast_test_flag(&opts, OPT_AOC_REQUEST)
06913       && !ast_strlen_zero(opt_args[OPT_ARG_AOC_REQUEST])) {
06914       if (strchr(opt_args[OPT_ARG_AOC_REQUEST], 's')) {
06915          pri_sr_set_aoc_charging_request(sr, PRI_AOC_REQUEST_S);
06916       }
06917       if (strchr(opt_args[OPT_ARG_AOC_REQUEST], 'd')) {
06918          pri_sr_set_aoc_charging_request(sr, PRI_AOC_REQUEST_D);
06919       }
06920       if (strchr(opt_args[OPT_ARG_AOC_REQUEST], 'e')) {
06921          pri_sr_set_aoc_charging_request(sr, PRI_AOC_REQUEST_E);
06922       }
06923    }
06924 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
06925 
06926    /* Setup the user tag for party id's from this device for this call. */
06927    if (p->pri->append_msn_to_user_tag) {
06928       snprintf(p->user_tag, sizeof(p->user_tag), "%s_%s", p->pri->initial_user_tag,
06929          p->pri->nodetype == PRI_NETWORK
06930             ? c + p->stripmsd + dp_strip
06931             : S_COR(ast->connected.id.number.valid,
06932                ast->connected.id.number.str, ""));
06933    } else {
06934       ast_copy_string(p->user_tag, p->pri->initial_user_tag, sizeof(p->user_tag));
06935    }
06936 
06937    /*
06938     * Replace the caller id tag from the channel creation
06939     * with the actual tag value.
06940     */
06941    ast_free(ast->caller.id.tag);
06942    ast->caller.id.tag = ast_strdup(p->user_tag);
06943 
06944    ldp_strip = 0;
06945    prilocaldialplan = p->pri->localdialplan - 1;
06946    if ((l != NULL) && (prilocaldialplan == -2 || prilocaldialplan == -3)) { /* compute dynamically */
06947       if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
06948          if (prilocaldialplan == -2) {
06949             ldp_strip = strlen(p->pri->internationalprefix);
06950          }
06951          prilocaldialplan = PRI_INTERNATIONAL_ISDN;
06952       } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
06953          if (prilocaldialplan == -2) {
06954             ldp_strip = strlen(p->pri->nationalprefix);
06955          }
06956          prilocaldialplan = PRI_NATIONAL_ISDN;
06957       } else {
06958          prilocaldialplan = PRI_LOCAL_ISDN;
06959       }
06960    }
06961    if (l != NULL) {
06962       while (*l > '9' && *l != '*' && *l != '#') {
06963          switch (*l) {
06964          case 'U':
06965             prilocaldialplan = (PRI_TON_UNKNOWN << 4) | (prilocaldialplan & 0xf);
06966             break;
06967          case 'I':
06968             prilocaldialplan = (PRI_TON_INTERNATIONAL << 4) | (prilocaldialplan & 0xf);
06969             break;
06970          case 'N':
06971             prilocaldialplan = (PRI_TON_NATIONAL << 4) | (prilocaldialplan & 0xf);
06972             break;
06973          case 'L':
06974             prilocaldialplan = (PRI_TON_NET_SPECIFIC << 4) | (prilocaldialplan & 0xf);
06975             break;
06976          case 'S':
06977             prilocaldialplan = (PRI_TON_SUBSCRIBER << 4) | (prilocaldialplan & 0xf);
06978             break;
06979          case 'V':
06980             prilocaldialplan = (PRI_TON_ABBREVIATED << 4) | (prilocaldialplan & 0xf);
06981             break;
06982          case 'R':
06983             prilocaldialplan = (PRI_TON_RESERVED << 4) | (prilocaldialplan & 0xf);
06984             break;
06985          case 'u':
06986             prilocaldialplan = PRI_NPI_UNKNOWN | (prilocaldialplan & 0xf0);
06987             break;
06988          case 'e':
06989             prilocaldialplan = PRI_NPI_E163_E164 | (prilocaldialplan & 0xf0);
06990             break;
06991          case 'x':
06992             prilocaldialplan = PRI_NPI_X121 | (prilocaldialplan & 0xf0);
06993             break;
06994          case 'f':
06995             prilocaldialplan = PRI_NPI_F69 | (prilocaldialplan & 0xf0);
06996             break;
06997          case 'n':
06998             prilocaldialplan = PRI_NPI_NATIONAL | (prilocaldialplan & 0xf0);
06999             break;
07000          case 'p':
07001             prilocaldialplan = PRI_NPI_PRIVATE | (prilocaldialplan & 0xf0);
07002             break;
07003          case 'r':
07004             prilocaldialplan = PRI_NPI_RESERVED | (prilocaldialplan & 0xf0);
07005             break;
07006          default:
07007             if (isalpha(*l)) {
07008                ast_log(LOG_WARNING,
07009                   "Unrecognized prilocaldialplan %s modifier: %c\n",
07010                   *l > 'Z' ? "NPI" : "TON", *l);
07011             }
07012             break;
07013          }
07014          l++;
07015       }
07016    }
07017    pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
07018       p->use_callingpres ? ast->connected.id.number.presentation : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
07019 
07020 #if defined(HAVE_PRI_SUBADDR)
07021    if (ast->connected.id.subaddress.valid) {
07022       struct pri_party_subaddress subaddress;
07023 
07024       memset(&subaddress, 0, sizeof(subaddress));
07025       sig_pri_party_subaddress_from_ast(&subaddress, &ast->connected.id.subaddress);
07026       pri_sr_set_caller_subaddress(sr, &subaddress);
07027    }
07028 #endif   /* defined(HAVE_PRI_SUBADDR) */
07029 
07030    sig_pri_redirecting_update(p, ast);
07031 
07032 #ifdef SUPPORT_USERUSER
07033    /* User-user info */
07034    useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
07035    if (useruser)
07036       pri_sr_set_useruser(sr, useruser);
07037 #endif
07038 
07039 #if defined(HAVE_PRI_CCSS)
07040    if (ast_cc_is_recall(ast, &core_id, sig_pri_cc_type_name)) {
07041       struct ast_cc_monitor *monitor;
07042       char device_name[AST_CHANNEL_NAME];
07043 
07044       /* This is a CC recall call. */
07045       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
07046       monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
07047       if (monitor) {
07048          struct sig_pri_cc_monitor_instance *instance;
07049 
07050          instance = monitor->private_data;
07051 
07052          /* If this fails then we have monitor instance ambiguity. */
07053          ast_assert(p->pri == instance->pri);
07054 
07055          if (pri_cc_call(p->pri->pri, instance->cc_id, p->call, sr)) {
07056             /* The CC recall call failed for some reason. */
07057             ast_log(LOG_WARNING, "Unable to setup CC recall call to device %s\n",
07058                device_name);
07059             ao2_ref(monitor, -1);
07060             pri_destroycall(p->pri->pri, p->call);
07061             p->call = NULL;
07062             pri_rel(p->pri);
07063             pri_sr_free(sr);
07064             return -1;
07065          }
07066          ao2_ref(monitor, -1);
07067       } else {
07068          core_id = -1;
07069       }
07070    } else
07071 #endif   /* defined(HAVE_PRI_CCSS) */
07072    {
07073       core_id = -1;
07074    }
07075    if (core_id == -1 && pri_setup(p->pri->pri, p->call, sr)) {
07076       ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n",
07077          c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
07078       pri_destroycall(p->pri->pri, p->call);
07079       p->call = NULL;
07080       pri_rel(p->pri);
07081       pri_sr_free(sr);
07082       return -1;
07083    }
07084    p->call_level = SIG_PRI_CALL_LEVEL_SETUP;
07085    pri_sr_free(sr);
07086    ast_setstate(ast, AST_STATE_DIALING);
07087    sig_pri_set_dialing(p, 1);
07088    pri_rel(p->pri);
07089    return 0;
07090 }
07091 
07092 int sig_pri_indicate(struct sig_pri_chan *p, struct ast_channel *chan, int condition, const void *data, size_t datalen)
07093 {
07094    int res = -1;
07095 
07096    switch (condition) {
07097    case AST_CONTROL_BUSY:
07098       if (p->priindication_oob || p->no_b_channel) {
07099          chan->hangupcause = AST_CAUSE_USER_BUSY;
07100          chan->_softhangup |= AST_SOFTHANGUP_DEV;
07101          res = 0;
07102          break;
07103       }
07104       res = sig_pri_play_tone(p, SIG_PRI_TONE_BUSY);
07105       if (p->call_level < SIG_PRI_CALL_LEVEL_ALERTING && !p->outgoing) {
07106          chan->hangupcause = AST_CAUSE_USER_BUSY;
07107          p->progress = 1;/* No need to send plain PROGRESS after this. */
07108          if (p->pri && p->pri->pri) {
07109             pri_grab(p, p->pri);
07110 #ifdef HAVE_PRI_PROG_W_CAUSE
07111             pri_progress_with_cause(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 1, chan->hangupcause);
07112 #else
07113             pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
07114 #endif
07115             pri_rel(p->pri);
07116          }
07117       }
07118       break;
07119    case AST_CONTROL_RINGING:
07120       if (p->call_level < SIG_PRI_CALL_LEVEL_ALERTING && !p->outgoing) {
07121          p->call_level = SIG_PRI_CALL_LEVEL_ALERTING;
07122          if (p->pri && p->pri->pri) {
07123             pri_grab(p, p->pri);
07124             pri_acknowledge(p->pri->pri,p->call, PVT_TO_CHANNEL(p),
07125                p->no_b_channel || p->digital ? 0 : 1);
07126             pri_rel(p->pri);
07127          }
07128       }
07129       res = sig_pri_play_tone(p, SIG_PRI_TONE_RINGTONE);
07130       if (chan->_state != AST_STATE_UP) {
07131          if (chan->_state != AST_STATE_RING)
07132             ast_setstate(chan, AST_STATE_RINGING);
07133       }
07134       break;
07135    case AST_CONTROL_PROCEEDING:
07136       ast_debug(1,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
07137       if (p->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING && !p->outgoing) {
07138          p->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
07139          if (p->pri && p->pri->pri) {
07140             pri_grab(p, p->pri);
07141             pri_proceeding(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 0);
07142             pri_rel(p->pri);
07143          }
07144       }
07145       /* don't continue in ast_indicate */
07146       res = 0;
07147       break;
07148    case AST_CONTROL_PROGRESS:
07149       ast_debug(1,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
07150       sig_pri_set_digital(p, 0); /* Digital-only calls isn't allowing any inband progress messages */
07151       if (!p->progress && p->call_level < SIG_PRI_CALL_LEVEL_ALERTING && !p->outgoing
07152          && !p->no_b_channel) {
07153          p->progress = 1;/* No need to send plain PROGRESS again. */
07154          if (p->pri && p->pri->pri) {
07155             pri_grab(p, p->pri);
07156 #ifdef HAVE_PRI_PROG_W_CAUSE
07157             pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, -1);  /* no cause at all */
07158 #else
07159             pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
07160 #endif
07161             pri_rel(p->pri);
07162          }
07163       }
07164       /* don't continue in ast_indicate */
07165       res = 0;
07166       break;
07167    case AST_CONTROL_INCOMPLETE:
07168       /* If we are connected or if we support overlap dialing, wait for additional digits */
07169       if (p->call_level == SIG_PRI_CALL_LEVEL_CONNECT || (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
07170          res = 0;
07171          break;
07172       }
07173       /* Otherwise, treat as congestion */
07174       chan->hangupcause = AST_CAUSE_INVALID_NUMBER_FORMAT;
07175       /* Falls through */
07176    case AST_CONTROL_CONGESTION:
07177       if (p->priindication_oob || p->no_b_channel) {
07178          /* There are many cause codes that generate an AST_CONTROL_CONGESTION. */
07179          switch (chan->hangupcause) {
07180          case AST_CAUSE_USER_BUSY:
07181          case AST_CAUSE_NORMAL_CLEARING:
07182          case 0:/* Cause has not been set. */
07183             /* Supply a more appropriate cause. */
07184             chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
07185             break;
07186          default:
07187             break;
07188          }
07189          chan->_softhangup |= AST_SOFTHANGUP_DEV;
07190          res = 0;
07191          break;
07192       }
07193       res = sig_pri_play_tone(p, SIG_PRI_TONE_CONGESTION);
07194       if (p->call_level < SIG_PRI_CALL_LEVEL_ALERTING && !p->outgoing) {
07195          /* There are many cause codes that generate an AST_CONTROL_CONGESTION. */
07196          switch (chan->hangupcause) {
07197          case AST_CAUSE_USER_BUSY:
07198          case AST_CAUSE_NORMAL_CLEARING:
07199          case 0:/* Cause has not been set. */
07200             /* Supply a more appropriate cause. */
07201             chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
07202             break;
07203          default:
07204             break;
07205          }
07206          p->progress = 1;/* No need to send plain PROGRESS after this. */
07207          if (p->pri && p->pri->pri) {
07208             pri_grab(p, p->pri);
07209 #ifdef HAVE_PRI_PROG_W_CAUSE
07210             pri_progress_with_cause(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 1, chan->hangupcause);
07211 #else
07212             pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
07213 #endif
07214             pri_rel(p->pri);
07215          }
07216       }
07217       break;
07218    case AST_CONTROL_HOLD:
07219       if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
07220          pri_grab(p, p->pri);
07221          res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_HOLD);
07222          pri_rel(p->pri);
07223       } else
07224          ast_moh_start(chan, data, p->mohinterpret);
07225       break;
07226    case AST_CONTROL_UNHOLD:
07227       if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
07228          pri_grab(p, p->pri);
07229          res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_RETRIEVAL);
07230          pri_rel(p->pri);
07231       } else
07232          ast_moh_stop(chan);
07233       break;
07234    case AST_CONTROL_SRCUPDATE:
07235       res = 0;
07236       break;
07237    case -1:
07238       res = sig_pri_play_tone(p, -1);
07239       break;
07240    case AST_CONTROL_CONNECTED_LINE:
07241       ast_debug(1, "Received AST_CONTROL_CONNECTED_LINE on %s\n", chan->name);
07242       if (p->pri) {
07243          struct pri_party_connected_line connected;
07244 
07245          pri_grab(p, p->pri);
07246          memset(&connected, 0, sizeof(connected));
07247          sig_pri_party_id_from_ast(&connected.id, &chan->connected.id);
07248 
07249          pri_connected_line_update(p->pri->pri, p->call, &connected);
07250          pri_rel(p->pri);
07251       }
07252       break;
07253    case AST_CONTROL_REDIRECTING:
07254       ast_debug(1, "Received AST_CONTROL_REDIRECTING on %s\n", chan->name);
07255       if (p->pri) {
07256          pri_grab(p, p->pri);
07257          sig_pri_redirecting_update(p, chan);
07258          pri_rel(p->pri);
07259       }
07260       break;
07261    case AST_CONTROL_AOC:
07262 #if defined(HAVE_PRI_AOC_EVENTS)
07263       {
07264          struct ast_aoc_decoded *decoded
07265             = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, chan);
07266          ast_debug(1, "Received AST_CONTROL_AOC on %s\n", chan->name);
07267          if (decoded && p->pri) {
07268             pri_grab(p, p->pri);
07269             switch (ast_aoc_get_msg_type(decoded)) {
07270             case AST_AOC_S:
07271                if (p->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
07272                   sig_pri_aoc_s_from_ast(p, decoded);
07273                }
07274                break;
07275             case AST_AOC_D:
07276                if (p->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
07277                   sig_pri_aoc_d_from_ast(p, decoded);
07278                }
07279                break;
07280             case AST_AOC_E:
07281                if (p->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
07282                   sig_pri_aoc_e_from_ast(p, decoded);
07283                }
07284                /* if hangup was delayed for this AOC-E msg, waiting_for_aoc
07285                 * will be set.  A hangup is already occuring via a timeout during
07286                 * this delay.  Instead of waiting for that timeout to occur, go ahead
07287                 * and initiate the softhangup since the delay is no longer necessary */
07288                if (p->waiting_for_aoce) {
07289                   p->waiting_for_aoce = 0;
07290                   ast_log(LOG_DEBUG,
07291                      "Received final AOC-E msg, continue with hangup on %s\n",
07292                      chan->name);
07293                   ast_softhangup_nolock(chan, AST_SOFTHANGUP_DEV);
07294                }
07295                break;
07296             case AST_AOC_REQUEST:
07297                /* We do not pass through AOC requests, So unless this
07298                 * is an AOC termination request it will be ignored */
07299                if (ast_aoc_get_termination_request(decoded)) {
07300                   pri_hangup(p->pri->pri, p->call, -1);
07301                }
07302                break;
07303             default:
07304                break;
07305             }
07306             pri_rel(p->pri);
07307          }
07308          ast_aoc_destroy_decoded(decoded);
07309       }
07310 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
07311       break;
07312    }
07313 
07314    return res;
07315 }
07316 
07317 int sig_pri_answer(struct sig_pri_chan *p, struct ast_channel *ast)
07318 {
07319    int res;
07320 
07321    /* Send a pri acknowledge */
07322    pri_grab(p, p->pri);
07323 #if defined(HAVE_PRI_AOC_EVENTS)
07324    if (p->aoc_s_request_invoke_id_valid) {
07325       /* if AOC-S was requested and the invoke id is still present on answer.  That means
07326        * no AOC-S rate list was provided, so send a NULL response which will indicate that
07327        * AOC-S is not available */
07328       pri_aoc_s_request_response_send(p->pri->pri, p->call,
07329          p->aoc_s_request_invoke_id, NULL);
07330       p->aoc_s_request_invoke_id_valid = 0;
07331    }
07332 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
07333    if (p->call_level < SIG_PRI_CALL_LEVEL_CONNECT) {
07334       p->call_level = SIG_PRI_CALL_LEVEL_CONNECT;
07335    }
07336    sig_pri_set_dialing(p, 0);
07337    sig_pri_open_media(p);
07338    res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
07339    pri_rel(p->pri);
07340    ast_setstate(ast, AST_STATE_UP);
07341    return res;
07342 }
07343 
07344 /*!
07345  * \internal
07346  * \brief Simple check if the channel is available to use.
07347  * \since 1.8
07348  *
07349  * \param pvt Private channel control structure.
07350  *
07351  * \retval 0 Interface not available.
07352  * \retval 1 Interface is available.
07353  */
07354 static int sig_pri_available_check(struct sig_pri_chan *pvt)
07355 {
07356    /*
07357     * If interface has a B channel and is available for use
07358     * then the channel is available.
07359     */
07360    if (!pvt->no_b_channel && sig_pri_is_chan_available(pvt)) {
07361       return 1;
07362    }
07363    return 0;
07364 }
07365 
07366 #if defined(HAVE_PRI_CALL_WAITING)
07367 /*!
07368  * \internal
07369  * \brief Get an available call waiting interface.
07370  * \since 1.8
07371  *
07372  * \param pri PRI span control structure.
07373  *
07374  * \note Assumes the pri->lock is already obtained.
07375  *
07376  * \retval cw Call waiting interface to use.
07377  * \retval NULL if no call waiting interface available.
07378  */
07379 static struct sig_pri_chan *sig_pri_cw_available(struct sig_pri_span *pri)
07380 {
07381    struct sig_pri_chan *cw;
07382    int idx;
07383 
07384    cw = NULL;
07385    if (pri->num_call_waiting_calls < pri->max_call_waiting_calls) {
07386       if (!pri->num_call_waiting_calls) {
07387          /*
07388           * There are no outstanding call waiting calls.  Check to see
07389           * if the span is in a congested state for the first call
07390           * waiting call.
07391           */
07392          for (idx = 0; idx < pri->numchans; ++idx) {
07393             if (pri->pvts[idx] && sig_pri_available_check(pri->pvts[idx])) {
07394                /* There is another channel that is available on this span. */
07395                return cw;
07396             }
07397          }
07398       }
07399       idx = pri_find_empty_nobch(pri);
07400       if (0 <= idx) {
07401          /* Setup the call waiting interface to use. */
07402          cw = pri->pvts[idx];
07403          cw->is_call_waiting = 1;
07404          sig_pri_init_config(cw, pri);
07405          ast_atomic_fetchadd_int(&pri->num_call_waiting_calls, 1);
07406       }
07407    }
07408    return cw;
07409 }
07410 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
07411 
07412 int sig_pri_available(struct sig_pri_chan **pvt, int is_specific_channel)
07413 {
07414    struct sig_pri_chan *p = *pvt;
07415    struct sig_pri_span *pri;
07416 
07417    if (!p->pri) {
07418       /* Something is wrong here.  A PRI channel without the pri pointer? */
07419       return 0;
07420    }
07421    pri = p->pri;
07422 
07423    ast_mutex_lock(&pri->lock);
07424    if (
07425 #if defined(HAVE_PRI_CALL_WAITING)
07426       /*
07427        * Only do call waiting calls if we have any
07428        * call waiting call outstanding.  We do not
07429        * want new calls to steal a B channel
07430        * freed for an earlier call waiting call.
07431        */
07432       !pri->num_call_waiting_calls &&
07433 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
07434       sig_pri_available_check(p)) {
07435       p->allocated = 1;
07436       ast_mutex_unlock(&pri->lock);
07437       return 1;
07438    }
07439 
07440 #if defined(HAVE_PRI_CALL_WAITING)
07441    if (!is_specific_channel) {
07442       struct sig_pri_chan *cw;
07443 
07444       cw = sig_pri_cw_available(pri);
07445       if (cw) {
07446          /* We have a call waiting interface to use instead. */
07447          cw->allocated = 1;
07448          *pvt = cw;
07449          ast_mutex_unlock(&pri->lock);
07450          return 1;
07451       }
07452    }
07453 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
07454    ast_mutex_unlock(&pri->lock);
07455    return 0;
07456 }
07457 
07458 /* If return 0, it means this function was able to handle it (pre setup digits).  If non zero, the user of this
07459  * functions should handle it normally (generate inband DTMF) */
07460 int sig_pri_digit_begin(struct sig_pri_chan *pvt, struct ast_channel *ast, char digit)
07461 {
07462    if (ast->_state == AST_STATE_DIALING) {
07463       if (pvt->call_level < SIG_PRI_CALL_LEVEL_OVERLAP) {
07464          unsigned int len;
07465 
07466          len = strlen(pvt->dialdest);
07467          if (len < sizeof(pvt->dialdest) - 1) {
07468             ast_debug(1, "Queueing digit '%c' since setup_ack not yet received\n",
07469                digit);
07470             pvt->dialdest[len++] = digit;
07471             pvt->dialdest[len] = '\0';
07472          } else {
07473             ast_log(LOG_WARNING,
07474                "Span %d: Deferred digit buffer overflow for digit '%c'.\n",
07475                pvt->pri->span, digit);
07476          }
07477          return 0;
07478       }
07479       if (pvt->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING) {
07480          pri_grab(pvt, pvt->pri);
07481          pri_information(pvt->pri->pri, pvt->call, digit);
07482          pri_rel(pvt->pri);
07483          return 0;
07484       }
07485       if (pvt->call_level < SIG_PRI_CALL_LEVEL_CONNECT) {
07486          ast_log(LOG_WARNING,
07487             "Span %d: Digit '%c' may be ignored by peer. (Call level:%u(%s))\n",
07488             pvt->pri->span, digit, pvt->call_level,
07489             sig_pri_call_level2str(pvt->call_level));
07490       }
07491    }
07492    return 1;
07493 }
07494 
07495 /*!
07496  * \brief DTMF dial string complete.
07497  * \since 1.8.11
07498  *
07499  * \param pvt sig_pri private channel structure.
07500  * \param ast Asterisk channel
07501  *
07502  * \note Channel and private lock are already held.
07503  *
07504  * \return Nothing
07505  */
07506 void sig_pri_dial_complete(struct sig_pri_chan *pvt, struct ast_channel *ast)
07507 {
07508    /* If we just completed 'w' deferred dialing digits, we need to answer now. */
07509    if (pvt->call_level == SIG_PRI_CALL_LEVEL_DEFER_DIAL) {
07510       pvt->call_level = SIG_PRI_CALL_LEVEL_CONNECT;
07511 
07512       sig_pri_open_media(pvt);
07513       {
07514          struct ast_frame f = {AST_FRAME_CONTROL, };
07515 
07516          if (pvt->calls->queue_control) {
07517             pvt->calls->queue_control(pvt->chan_pvt, AST_CONTROL_ANSWER);
07518          }
07519 
07520          f.subclass.integer = AST_CONTROL_ANSWER;
07521          ast_queue_frame(ast, &f);
07522       }
07523       sig_pri_set_dialing(pvt, 0);
07524       /* Enable echo cancellation if it's not on already */
07525       sig_pri_set_echocanceller(pvt, 1);
07526    }
07527 }
07528 
07529 #if defined(HAVE_PRI_MWI)
07530 /*!
07531  * \internal
07532  * \brief Send a MWI indication to the given span.
07533  * \since 1.8
07534  *
07535  * \param pri PRI span control structure.
07536  * \param mbox_number Mailbox number
07537  * \param mbox_context Mailbox context
07538  * \param num_messages Number of messages waiting.
07539  *
07540  * \return Nothing
07541  */
07542 static void sig_pri_send_mwi_indication(struct sig_pri_span *pri, const char *mbox_number, const char *mbox_context, int num_messages)
07543 {
07544    struct pri_party_id mailbox;
07545 
07546    ast_debug(1, "Send MWI indication for %s@%s num_messages:%d\n", mbox_number,
07547       mbox_context, num_messages);
07548 
07549    memset(&mailbox, 0, sizeof(mailbox));
07550    mailbox.number.valid = 1;
07551    mailbox.number.presentation = PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
07552    mailbox.number.plan = (PRI_TON_UNKNOWN << 4) | PRI_NPI_UNKNOWN;
07553    ast_copy_string(mailbox.number.str, mbox_number, sizeof(mailbox.number.str));
07554 
07555    ast_mutex_lock(&pri->lock);
07556    pri_mwi_indicate(pri->pri, &mailbox, 1 /* speech */, num_messages, NULL, NULL, -1, 0);
07557    ast_mutex_unlock(&pri->lock);
07558 }
07559 #endif   /* defined(HAVE_PRI_MWI) */
07560 
07561 #if defined(HAVE_PRI_MWI)
07562 /*!
07563  * \internal
07564  * \brief MWI subscription event callback.
07565  * \since 1.8
07566  *
07567  * \param event the event being passed to the subscriber
07568  * \param userdata the data provider in the call to ast_event_subscribe()
07569  *
07570  * \return Nothing
07571  */
07572 static void sig_pri_mwi_event_cb(const struct ast_event *event, void *userdata)
07573 {
07574    struct sig_pri_span *pri = userdata;
07575    const char *mbox_context;
07576    const char *mbox_number;
07577    int num_messages;
07578 
07579    mbox_number = ast_event_get_ie_str(event, AST_EVENT_IE_MAILBOX);
07580    if (ast_strlen_zero(mbox_number)) {
07581       return;
07582    }
07583    mbox_context = ast_event_get_ie_str(event, AST_EVENT_IE_CONTEXT);
07584    if (ast_strlen_zero(mbox_context)) {
07585       return;
07586    }
07587    num_messages = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
07588    sig_pri_send_mwi_indication(pri, mbox_number, mbox_context, num_messages);
07589 }
07590 #endif   /* defined(HAVE_PRI_MWI) */
07591 
07592 #if defined(HAVE_PRI_MWI)
07593 /*!
07594  * \internal
07595  * \brief Send update MWI indications from the event cache.
07596  * \since 1.8
07597  *
07598  * \param pri PRI span control structure.
07599  *
07600  * \return Nothing
07601  */
07602 static void sig_pri_mwi_cache_update(struct sig_pri_span *pri)
07603 {
07604    int idx;
07605    int num_messages;
07606    struct ast_event *event;
07607 
07608    for (idx = 0; idx < ARRAY_LEN(pri->mbox); ++idx) {
07609       if (!pri->mbox[idx].sub) {
07610          /* There are no more mailboxes on this span. */
07611          break;
07612       }
07613 
07614       event = ast_event_get_cached(AST_EVENT_MWI,
07615          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, pri->mbox[idx].number,
07616          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, pri->mbox[idx].context,
07617          AST_EVENT_IE_END);
07618       if (!event) {
07619          /* No cached event for this mailbox. */
07620          continue;
07621       }
07622       num_messages = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
07623       sig_pri_send_mwi_indication(pri, pri->mbox[idx].number, pri->mbox[idx].context,
07624          num_messages);
07625       ast_event_destroy(event);
07626    }
07627 }
07628 #endif   /* defined(HAVE_PRI_MWI) */
07629 
07630 /*!
07631  * \brief Stop PRI span.
07632  * \since 1.8
07633  *
07634  * \param pri PRI span control structure.
07635  *
07636  * \return Nothing
07637  */
07638 void sig_pri_stop_pri(struct sig_pri_span *pri)
07639 {
07640 #if defined(HAVE_PRI_MWI)
07641    int idx;
07642 #endif   /* defined(HAVE_PRI_MWI) */
07643 
07644 #if defined(HAVE_PRI_MWI)
07645    for (idx = 0; idx < ARRAY_LEN(pri->mbox); ++idx) {
07646       if (pri->mbox[idx].sub) {
07647          pri->mbox[idx].sub = ast_event_unsubscribe(pri->mbox[idx].sub);
07648       }
07649    }
07650 #endif   /* defined(HAVE_PRI_MWI) */
07651 }
07652 
07653 /*!
07654  * \internal
07655  * \brief qsort comparison function.
07656  * \since 1.8
07657  *
07658  * \param left Ptr to sig_pri_chan ptr to compare.
07659  * \param right Ptr to sig_pri_chan ptr to compare.
07660  *
07661  * \retval <0 if left < right.
07662  * \retval =0 if left == right.
07663  * \retval >0 if left > right.
07664  */
07665 static int sig_pri_cmp_pri_chans(const void *left, const void *right)
07666 {
07667    const struct sig_pri_chan *pvt_left;
07668    const struct sig_pri_chan *pvt_right;
07669 
07670    pvt_left = *(struct sig_pri_chan **) left;
07671    pvt_right = *(struct sig_pri_chan **) right;
07672    if (!pvt_left) {
07673       if (!pvt_right) {
07674          return 0;
07675       }
07676       return 1;
07677    }
07678    if (!pvt_right) {
07679       return -1;
07680    }
07681 
07682    return pvt_left->channel - pvt_right->channel;
07683 }
07684 
07685 /*!
07686  * \internal
07687  * \brief Sort the PRI B channel private pointer array.
07688  * \since 1.8
07689  *
07690  * \param pri PRI span control structure.
07691  *
07692  * \details
07693  * Since the chan_dahdi.conf file can declare channels in any order, we need to sort
07694  * the private channel pointer array.
07695  *
07696  * \return Nothing
07697  */
07698 static void sig_pri_sort_pri_chans(struct sig_pri_span *pri)
07699 {
07700    qsort(&pri->pvts, pri->numchans, sizeof(pri->pvts[0]), sig_pri_cmp_pri_chans);
07701 }
07702 
07703 int sig_pri_start_pri(struct sig_pri_span *pri)
07704 {
07705    int x;
07706    int i;
07707 #if defined(HAVE_PRI_MWI)
07708    char *saveptr;
07709    char *mbox_number;
07710    char *mbox_context;
07711    struct ast_str *mwi_description = ast_str_alloca(64);
07712 #endif   /* defined(HAVE_PRI_MWI) */
07713 
07714 #if defined(HAVE_PRI_MWI)
07715    /* Prepare the mbox[] for use. */
07716    for (i = 0; i < ARRAY_LEN(pri->mbox); ++i) {
07717       if (pri->mbox[i].sub) {
07718          pri->mbox[i].sub = ast_event_unsubscribe(pri->mbox[i].sub);
07719       }
07720    }
07721 #endif   /* defined(HAVE_PRI_MWI) */
07722 
07723    ast_mutex_init(&pri->lock);
07724    sig_pri_sort_pri_chans(pri);
07725 
07726 #if defined(HAVE_PRI_MWI)
07727    /*
07728     * Split the mwi_mailboxes configuration string into the mbox[]:
07729     * mailbox_number[@context]{,mailbox_number[@context]}
07730     */
07731    i = 0;
07732    saveptr = pri->mwi_mailboxes;
07733    while (i < ARRAY_LEN(pri->mbox)) {
07734       mbox_number = strsep(&saveptr, ",");
07735       if (!mbox_number) {
07736          break;
07737       }
07738       /* Split the mailbox_number and context */
07739       mbox_context = strchr(mbox_number, '@');
07740       if (mbox_context) {
07741          *mbox_context++ = '\0';
07742          mbox_context = ast_strip(mbox_context);
07743       }
07744       mbox_number = ast_strip(mbox_number);
07745       if (ast_strlen_zero(mbox_number)) {
07746          /* There is no mailbox number.  Skip it. */
07747          continue;
07748       }
07749       if (ast_strlen_zero(mbox_context)) {
07750          /* There was no context so use the default. */
07751          mbox_context = "default";
07752       }
07753 
07754       /* Fill the mbox[] element. */
07755       ast_str_set(&mwi_description, -1, "%s span %d[%d] MWI mailbox %s@%s",
07756          sig_pri_cc_type_name, pri->span, i, mbox_number, mbox_context);
07757       pri->mbox[i].sub = ast_event_subscribe(AST_EVENT_MWI, sig_pri_mwi_event_cb,
07758          ast_str_buffer(mwi_description), pri,
07759          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mbox_number,
07760          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, mbox_context,
07761          AST_EVENT_IE_END);
07762       if (!pri->mbox[i].sub) {
07763          ast_log(LOG_ERROR, "%s span %d could not subscribe to MWI events for %s@%s.",
07764             sig_pri_cc_type_name, pri->span, mbox_number, mbox_context);
07765          continue;
07766       }
07767       pri->mbox[i].number = mbox_number;
07768       pri->mbox[i].context = mbox_context;
07769       ++i;
07770    }
07771 #endif   /* defined(HAVE_PRI_MWI) */
07772 
07773    for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
07774       if (pri->fds[i] == -1) {
07775          break;
07776       }
07777 
07778       switch (pri->sig) {
07779       case SIG_BRI:
07780          pri->dchans[i] = pri_new_bri(pri->fds[i], 1, pri->nodetype, pri->switchtype);
07781          break;
07782       case SIG_BRI_PTMP:
07783          pri->dchans[i] = pri_new_bri(pri->fds[i], 0, pri->nodetype, pri->switchtype);
07784          break;
07785       default:
07786          pri->dchans[i] = pri_new(pri->fds[i], pri->nodetype, pri->switchtype);
07787 #if defined(HAVE_PRI_SERVICE_MESSAGES)
07788          if (pri->enable_service_message_support) {
07789             pri_set_service_message_support(pri->dchans[i], 1);
07790          }
07791 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
07792          break;
07793       }
07794 
07795       pri_set_overlapdial(pri->dchans[i], (pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING) ? 1 : 0);
07796 #ifdef HAVE_PRI_PROG_W_CAUSE
07797       pri_set_chan_mapping_logical(pri->dchans[i], pri->qsigchannelmapping == DAHDI_CHAN_MAPPING_LOGICAL);
07798 #endif
07799 #ifdef HAVE_PRI_INBANDDISCONNECT
07800       pri_set_inbanddisconnect(pri->dchans[i], pri->inbanddisconnect);
07801 #endif
07802       /* Enslave to master if appropriate */
07803       if (i)
07804          pri_enslave(pri->dchans[0], pri->dchans[i]);
07805       if (!pri->dchans[i]) {
07806          if (pri->fds[i] > 0)
07807             close(pri->fds[i]);
07808          pri->fds[i] = -1;
07809          ast_log(LOG_ERROR, "Unable to create PRI structure\n");
07810          return -1;
07811       }
07812       pri_set_debug(pri->dchans[i], SIG_PRI_DEBUG_DEFAULT);
07813       pri_set_nsf(pri->dchans[i], pri->nsf);
07814 #ifdef PRI_GETSET_TIMERS
07815       for (x = 0; x < PRI_MAX_TIMERS; x++) {
07816          if (pri->pritimers[x] != 0)
07817             pri_set_timer(pri->dchans[i], x, pri->pritimers[x]);
07818       }
07819 #endif
07820    }
07821 
07822    /* Assume primary is the one we use */
07823    pri->pri = pri->dchans[0];
07824 
07825 #if defined(HAVE_PRI_CALL_HOLD)
07826    pri_hold_enable(pri->pri, 1);
07827 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
07828 #if defined(HAVE_PRI_CALL_REROUTING)
07829    pri_reroute_enable(pri->pri, 1);
07830 #endif   /* defined(HAVE_PRI_CALL_REROUTING) */
07831 #if defined(HAVE_PRI_HANGUP_FIX)
07832    pri_hangup_fix_enable(pri->pri, 1);
07833 #endif   /* defined(HAVE_PRI_HANGUP_FIX) */
07834 #if defined(HAVE_PRI_CCSS)
07835    pri_cc_enable(pri->pri, 1);
07836    pri_cc_recall_mode(pri->pri, pri->cc_ptmp_recall_mode);
07837    pri_cc_retain_signaling_req(pri->pri, pri->cc_qsig_signaling_link_req);
07838    pri_cc_retain_signaling_rsp(pri->pri, pri->cc_qsig_signaling_link_rsp);
07839 #endif   /* defined(HAVE_PRI_CCSS) */
07840 #if defined(HAVE_PRI_TRANSFER)
07841    pri_transfer_enable(pri->pri, 1);
07842 #endif   /* defined(HAVE_PRI_TRANSFER) */
07843 #if defined(HAVE_PRI_AOC_EVENTS)
07844    pri_aoc_events_enable(pri->pri, 1);
07845 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
07846 #if defined(HAVE_PRI_CALL_WAITING)
07847    pri_connect_ack_enable(pri->pri, 1);
07848 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
07849 #if defined(HAVE_PRI_MCID)
07850    pri_mcid_enable(pri->pri, 1);
07851 #endif   /* defined(HAVE_PRI_MCID) */
07852 #if defined(HAVE_PRI_L2_PERSISTENCE)
07853    pri_persistent_layer2_option(pri->pri, pri->l2_persistence);
07854 #endif   /* defined(HAVE_PRI_L2_PERSISTENCE) */
07855 
07856    pri->resetpos = -1;
07857    if (ast_pthread_create_background(&pri->master, NULL, pri_dchannel, pri)) {
07858       for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
07859          if (!pri->dchans[i])
07860             break;
07861          if (pri->fds[i] > 0)
07862             close(pri->fds[i]);
07863          pri->fds[i] = -1;
07864       }
07865       ast_log(LOG_ERROR, "Unable to spawn D-channel: %s\n", strerror(errno));
07866       return -1;
07867    }
07868 
07869 #if defined(HAVE_PRI_MWI)
07870    /*
07871     * Send the initial MWI indications from the event cache for this span.
07872     *
07873     * If we were loaded after app_voicemail the event would already be in
07874     * the cache.  If we were loaded before app_voicemail the event would not
07875     * be in the cache yet and app_voicemail will send the event when it
07876     * gets loaded.
07877     */
07878    sig_pri_mwi_cache_update(pri);
07879 #endif   /* defined(HAVE_PRI_MWI) */
07880 
07881    return 0;
07882 }
07883 
07884 /*!
07885  * \brief Notify new alarm status.
07886  *
07887  * \param p Channel private pointer.
07888  * \param noalarm Non-zero if not in alarm mode.
07889  * 
07890  * \note Assumes the sig_pri_lock_private(p) is already obtained.
07891  *
07892  * \return Nothing
07893  */
07894 void sig_pri_chan_alarm_notify(struct sig_pri_chan *p, int noalarm)
07895 {
07896    pri_grab(p, p->pri);
07897    sig_pri_set_alarm(p, !noalarm);
07898    if (!noalarm) {
07899       if (pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
07900          /* T309 is not enabled : destroy calls when alarm occurs */
07901          if (p->call) {
07902             pri_destroycall(p->pri->pri, p->call);
07903             p->call = NULL;
07904          }
07905          if (p->owner)
07906             p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
07907       }
07908    }
07909    sig_pri_span_devstate_changed(p->pri);
07910    pri_rel(p->pri);
07911 }
07912 
07913 /*!
07914  * \brief Determine if layer 1 alarms are ignored.
07915  *
07916  * \param p Channel private pointer.
07917  *
07918  * \return TRUE if the alarm is ignored.
07919  */
07920 int sig_pri_is_alarm_ignored(struct sig_pri_span *pri)
07921 {
07922    return pri->layer1_ignored;
07923 }
07924 
07925 struct sig_pri_chan *sig_pri_chan_new(void *pvt_data, struct sig_pri_callback *callback, struct sig_pri_span *pri, int logicalspan, int channo, int trunkgroup)
07926 {
07927    struct sig_pri_chan *p;
07928 
07929    p = ast_calloc(1, sizeof(*p));
07930    if (!p)
07931       return p;
07932 
07933    p->logicalspan = logicalspan;
07934    p->prioffset = channo;
07935    p->mastertrunkgroup = trunkgroup;
07936 
07937    p->calls = callback;
07938    p->chan_pvt = pvt_data;
07939 
07940    p->pri = pri;
07941 
07942    return p;
07943 }
07944 
07945 /*!
07946  * \brief Delete the sig_pri private channel structure.
07947  * \since 1.8
07948  *
07949  * \param doomed sig_pri private channel structure to delete.
07950  *
07951  * \return Nothing
07952  */
07953 void sig_pri_chan_delete(struct sig_pri_chan *doomed)
07954 {
07955    ast_free(doomed);
07956 }
07957 
07958 #define SIG_PRI_SC_HEADER  "%-4s %4s %-4s %-4s %-10s %-4s %s\n"
07959 #define SIG_PRI_SC_LINE     "%4d %4d %-4s %-4s %-10s %-4s %s"
07960 void sig_pri_cli_show_channels_header(int fd)
07961 {
07962    ast_cli(fd, SIG_PRI_SC_HEADER, "PRI",  "",     "B",    "Chan", "Call",  "PRI",  "Channel");
07963    ast_cli(fd, SIG_PRI_SC_HEADER, "Span", "Chan", "Chan", "Idle", "Level", "Call", "Name");
07964 }
07965 
07966 void sig_pri_cli_show_channels(int fd, struct sig_pri_span *pri)
07967 {
07968    char line[256];
07969    int idx;
07970    struct sig_pri_chan *pvt;
07971 
07972    ast_mutex_lock(&pri->lock);
07973    for (idx = 0; idx < pri->numchans; ++idx) {
07974       if (!pri->pvts[idx]) {
07975          continue;
07976       }
07977       pvt = pri->pvts[idx];
07978       sig_pri_lock_private(pvt);
07979       sig_pri_lock_owner(pri, idx);
07980       if (pvt->no_b_channel && sig_pri_is_chan_available(pvt)) {
07981          /* Don't show held/call-waiting channels if they are not in use. */
07982          sig_pri_unlock_private(pvt);
07983          continue;
07984       }
07985 
07986       snprintf(line, sizeof(line), SIG_PRI_SC_LINE,
07987          pri->span,
07988          pvt->channel,
07989          pvt->no_b_channel ? "No" : "Yes",/* Has media */
07990          sig_pri_is_chan_available(pvt) ? "Yes" : "No",
07991          sig_pri_call_level2str(pvt->call_level),
07992          pvt->call ? "Yes" : "No",
07993          pvt->owner ? pvt->owner->name : "");
07994 
07995       if (pvt->owner) {
07996          ast_channel_unlock(pvt->owner);
07997       }
07998       sig_pri_unlock_private(pvt);
07999 
08000       ast_mutex_unlock(&pri->lock);
08001       ast_cli(fd, "%s\n", line);
08002       ast_mutex_lock(&pri->lock);
08003    }
08004    ast_mutex_unlock(&pri->lock);
08005 }
08006 
08007 static void build_status(char *s, size_t len, int status, int active)
08008 {
08009    if (!s || len < 1) {
08010       return;
08011    }
08012    s[0] = '\0';
08013    if (!(status & DCHAN_NOTINALARM))
08014       strncat(s, "In Alarm, ", len - strlen(s) - 1);
08015    if (status & DCHAN_UP)
08016       strncat(s, "Up", len - strlen(s) - 1);
08017    else
08018       strncat(s, "Down", len - strlen(s) - 1);
08019    if (active)
08020       strncat(s, ", Active", len - strlen(s) - 1);
08021    else
08022       strncat(s, ", Standby", len - strlen(s) - 1);
08023    s[len - 1] = '\0';
08024 }
08025 
08026 void sig_pri_cli_show_spans(int fd, int span, struct sig_pri_span *pri)
08027 {
08028    char status[256];
08029    int x;
08030    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
08031       if (pri->dchans[x]) {
08032          build_status(status, sizeof(status), pri->dchanavail[x], pri->dchans[x] == pri->pri);
08033          ast_cli(fd, "PRI span %d/%d: %s\n", span, x, status);
08034       }
08035    }
08036 }
08037 
08038 void sig_pri_cli_show_span(int fd, int *dchannels, struct sig_pri_span *pri)
08039 {
08040    int x;
08041    char status[256];
08042 
08043    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
08044       if (pri->dchans[x]) {
08045 #ifdef PRI_DUMP_INFO_STR
08046          char *info_str = NULL;
08047 #endif
08048          ast_cli(fd, "%s D-channel: %d\n", pri_order(x), dchannels[x]);
08049          build_status(status, sizeof(status), pri->dchanavail[x], pri->dchans[x] == pri->pri);
08050          ast_cli(fd, "Status: %s\n", status);
08051          ast_mutex_lock(&pri->lock);
08052 #ifdef PRI_DUMP_INFO_STR
08053          info_str = pri_dump_info_str(pri->pri);
08054          if (info_str) {
08055             ast_cli(fd, "%s", info_str);
08056             ast_std_free(info_str);
08057          }
08058 #else
08059          pri_dump_info(pri->pri);
08060 #endif
08061          ast_mutex_unlock(&pri->lock);
08062          ast_cli(fd, "Overlap Recv: %s\n\n", (pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)?"Yes":"No");
08063          ast_cli(fd, "\n");
08064       }
08065    }
08066 }
08067 
08068 int pri_send_keypad_facility_exec(struct sig_pri_chan *p, const char *digits)
08069 {
08070    sig_pri_lock_private(p);
08071 
08072    if (!p->pri || !p->call) {
08073       ast_debug(1, "Unable to find pri or call on channel!\n");
08074       sig_pri_unlock_private(p);
08075       return -1;
08076    }
08077 
08078    pri_grab(p, p->pri);
08079    pri_keypad_facility(p->pri->pri, p->call, digits);
08080    pri_rel(p->pri);
08081 
08082    sig_pri_unlock_private(p);
08083 
08084    return 0;
08085 }
08086 
08087 int pri_send_callrerouting_facility_exec(struct sig_pri_chan *p, enum ast_channel_state chanstate, const char *destination, const char *original, const char *reason)
08088 {
08089    int res;
08090 
08091    sig_pri_lock_private(p);
08092 
08093    if (!p->pri || !p->call) {
08094       ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
08095       sig_pri_unlock_private(p);
08096       return -1;
08097    }
08098 
08099    pri_grab(p, p->pri);
08100    res = pri_callrerouting_facility(p->pri->pri, p->call, destination, original, reason);
08101    pri_rel(p->pri);
08102 
08103    sig_pri_unlock_private(p);
08104 
08105    return res;
08106 }
08107 
08108 #if defined(HAVE_PRI_SERVICE_MESSAGES)
08109 int pri_maintenance_bservice(struct pri *pri, struct sig_pri_chan *p, int changestatus)
08110 {
08111    int channel = PVT_TO_CHANNEL(p);
08112    int span = PRI_SPAN(channel);
08113 
08114    return pri_maintenance_service(pri, span, channel, changestatus);
08115 }
08116 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
08117 
08118 void sig_pri_fixup(struct ast_channel *oldchan, struct ast_channel *newchan, struct sig_pri_chan *pchan)
08119 {
08120    if (pchan->owner == oldchan) {
08121       pchan->owner = newchan;
08122    }
08123 }
08124 
08125 #if defined(HAVE_PRI_CCSS)
08126 /*!
08127  * \brief PRI CC agent initialization.
08128  * \since 1.8
08129  *
08130  * \param agent CC core agent control.
08131  * \param pvt_chan Original channel the agent will attempt to recall.
08132  *
08133  * \details
08134  * This callback is called when the CC core is initialized.  Agents should allocate
08135  * any private data necessary for the call and assign it to the private_data
08136  * on the agent.  Additionally, if any ast_cc_agent_flags are pertinent to the
08137  * specific agent type, they should be set in this function as well.
08138  *
08139  * \retval 0 on success.
08140  * \retval -1 on error.
08141  */
08142 int sig_pri_cc_agent_init(struct ast_cc_agent *agent, struct sig_pri_chan *pvt_chan)
08143 {
08144    struct sig_pri_cc_agent_prv *cc_pvt;
08145 
08146    cc_pvt = ast_calloc(1, sizeof(*cc_pvt));
08147    if (!cc_pvt) {
08148       return -1;
08149    }
08150 
08151    ast_mutex_lock(&pvt_chan->pri->lock);
08152    cc_pvt->pri = pvt_chan->pri;
08153    cc_pvt->cc_id = pri_cc_available(pvt_chan->pri->pri, pvt_chan->call);
08154    ast_mutex_unlock(&pvt_chan->pri->lock);
08155    if (cc_pvt->cc_id == -1) {
08156       ast_free(cc_pvt);
08157       return -1;
08158    }
08159    agent->private_data = cc_pvt;
08160    return 0;
08161 }
08162 #endif   /* defined(HAVE_PRI_CCSS) */
08163 
08164 #if defined(HAVE_PRI_CCSS)
08165 /*!
08166  * \brief Start the offer timer.
08167  * \since 1.8
08168  *
08169  * \param agent CC core agent control.
08170  *
08171  * \details
08172  * This is called by the core when the caller hangs up after
08173  * a call for which CC may be requested. The agent should
08174  * begin the timer as configured.
08175  *
08176  * The primary reason why this functionality is left to
08177  * the specific agent implementations is due to the differing
08178  * use of schedulers throughout the code. Some channel drivers
08179  * may already have a scheduler context they wish to use, and
08180  * amongst those, some may use the ast_sched API while others
08181  * may use the ast_sched_thread API, which are incompatible.
08182  *
08183  * \retval 0 on success.
08184  * \retval -1 on error.
08185  */
08186 int sig_pri_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
08187 {
08188    /* libpri maintains it's own offer timer in the form of T_RETENTION. */
08189    return 0;
08190 }
08191 #endif   /* defined(HAVE_PRI_CCSS) */
08192 
08193 #if defined(HAVE_PRI_CCSS)
08194 /*!
08195  * \brief Stop the offer timer.
08196  * \since 1.8
08197  *
08198  * \param agent CC core agent control.
08199  *
08200  * \details
08201  * This callback is called by the CC core when the caller
08202  * has requested CC.
08203  *
08204  * \retval 0 on success.
08205  * \retval -1 on error.
08206  */
08207 int sig_pri_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
08208 {
08209    /* libpri maintains it's own offer timer in the form of T_RETENTION. */
08210    return 0;
08211 }
08212 #endif   /* defined(HAVE_PRI_CCSS) */
08213 
08214 #if defined(HAVE_PRI_CCSS)
08215 /*!
08216  * \brief Response to a CC request.
08217  * \since 1.8
08218  *
08219  * \param agent CC core agent control.
08220  * \param reason CC request response status.
08221  *
08222  * \details
08223  * When the core receives knowledge that a called
08224  * party has accepted a CC request, it will call
08225  * this callback.  The core may also call this
08226  * if there is some error when attempting to process
08227  * the incoming CC request.
08228  *
08229  * The duty of this is to issue a propper response to a
08230  * CC request from the caller by acknowledging receipt
08231  * of that request or rejecting it.
08232  *
08233  * \return Nothing
08234  */
08235 void sig_pri_cc_agent_req_rsp(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
08236 {
08237    struct sig_pri_cc_agent_prv *cc_pvt;
08238    int res;
08239    int status;
08240    const char *failed_msg;
08241    static const char *failed_to_send = "Failed to send the CC request response.";
08242    static const char *not_accepted = "The core declined the CC request.";
08243 
08244    cc_pvt = agent->private_data;
08245    ast_mutex_lock(&cc_pvt->pri->lock);
08246    if (cc_pvt->cc_request_response_pending) {
08247       cc_pvt->cc_request_response_pending = 0;
08248 
08249       /* Convert core response reason to ISDN response status. */
08250       status = 2;/* short_term_denial */
08251       switch (reason) {
08252       case AST_CC_AGENT_RESPONSE_SUCCESS:
08253          status = 0;/* success */
08254          break;
08255       case AST_CC_AGENT_RESPONSE_FAILURE_INVALID:
08256          status = 2;/* short_term_denial */
08257          break;
08258       case AST_CC_AGENT_RESPONSE_FAILURE_TOO_MANY:
08259          status = 5;/* queue_full */
08260          break;
08261       }
08262 
08263       res = pri_cc_req_rsp(cc_pvt->pri->pri, cc_pvt->cc_id, status);
08264       if (!status) {
08265          /* CC core request was accepted. */
08266          if (res) {
08267             failed_msg = failed_to_send;
08268          } else {
08269             failed_msg = NULL;
08270          }
08271       } else {
08272          /* CC core request was declined. */
08273          if (res) {
08274             failed_msg = failed_to_send;
08275          } else {
08276             failed_msg = not_accepted;
08277          }
08278       }
08279    } else {
08280       failed_msg = NULL;
08281    }
08282    ast_mutex_unlock(&cc_pvt->pri->lock);
08283    if (failed_msg) {
08284       ast_cc_failed(agent->core_id, "%s agent: %s", sig_pri_cc_type_name, failed_msg);
08285    }
08286 }
08287 #endif   /* defined(HAVE_PRI_CCSS) */
08288 
08289 #if defined(HAVE_PRI_CCSS)
08290 /*!
08291  * \brief Request the status of the agent's device.
08292  * \since 1.8
08293  *
08294  * \param agent CC core agent control.
08295  *
08296  * \details
08297  * Asynchronous request for the status of any caller
08298  * which may be a valid caller for the CC transaction.
08299  * Status responses should be made using the
08300  * ast_cc_status_response function.
08301  *
08302  * \retval 0 on success.
08303  * \retval -1 on error.
08304  */
08305 int sig_pri_cc_agent_status_req(struct ast_cc_agent *agent)
08306 {
08307    struct sig_pri_cc_agent_prv *cc_pvt;
08308 
08309    cc_pvt = agent->private_data;
08310    ast_mutex_lock(&cc_pvt->pri->lock);
08311    pri_cc_status_req(cc_pvt->pri->pri, cc_pvt->cc_id);
08312    ast_mutex_unlock(&cc_pvt->pri->lock);
08313    return 0;
08314 }
08315 #endif   /* defined(HAVE_PRI_CCSS) */
08316 
08317 #if defined(HAVE_PRI_CCSS)
08318 /*!
08319  * \brief Request for an agent's phone to stop ringing.
08320  * \since 1.8
08321  *
08322  * \param agent CC core agent control.
08323  *
08324  * \details
08325  * The usefulness of this is quite limited. The only specific
08326  * known case for this is if Asterisk requests CC over an ISDN
08327  * PTMP link as the TE side. If other phones are in the same
08328  * recall group as the Asterisk server, and one of those phones
08329  * picks up the recall notice, then Asterisk will receive a
08330  * "stop ringing" notification from the NT side of the PTMP
08331  * link. This indication needs to be passed to the phone
08332  * on the other side of the Asterisk server which originally
08333  * placed the call so that it will stop ringing. Since the
08334  * phone may be of any type, it is necessary to have a callback
08335  * that the core can know about.
08336  *
08337  * \retval 0 on success.
08338  * \retval -1 on error.
08339  */
08340 int sig_pri_cc_agent_stop_ringing(struct ast_cc_agent *agent)
08341 {
08342    struct sig_pri_cc_agent_prv *cc_pvt;
08343 
08344    cc_pvt = agent->private_data;
08345    ast_mutex_lock(&cc_pvt->pri->lock);
08346    pri_cc_stop_alerting(cc_pvt->pri->pri, cc_pvt->cc_id);
08347    ast_mutex_unlock(&cc_pvt->pri->lock);
08348    return 0;
08349 }
08350 #endif   /* defined(HAVE_PRI_CCSS) */
08351 
08352 #if defined(HAVE_PRI_CCSS)
08353 /*!
08354  * \brief Let the caller know that the callee has become free
08355  * but that the caller cannot attempt to call back because
08356  * he is either busy or there is congestion on his line.
08357  * \since 1.8
08358  *
08359  * \param agent CC core agent control.
08360  *
08361  * \details
08362  * This is something that really only affects a scenario where
08363  * a phone places a call over ISDN PTMP to Asterisk, who then
08364  * connects over PTMP again to the ISDN network. For most agent
08365  * types, there is no need to implement this callback at all
08366  * because they don't really need to actually do anything in
08367  * this situation. If you're having trouble understanding what
08368  * the purpose of this callback is, then you can be safe simply
08369  * not implementing it.
08370  *
08371  * \retval 0 on success.
08372  * \retval -1 on error.
08373  */
08374 int sig_pri_cc_agent_party_b_free(struct ast_cc_agent *agent)
08375 {
08376    struct sig_pri_cc_agent_prv *cc_pvt;
08377 
08378    cc_pvt = agent->private_data;
08379    ast_mutex_lock(&cc_pvt->pri->lock);
08380    pri_cc_b_free(cc_pvt->pri->pri, cc_pvt->cc_id);
08381    ast_mutex_unlock(&cc_pvt->pri->lock);
08382    return 0;
08383 }
08384 #endif   /* defined(HAVE_PRI_CCSS) */
08385 
08386 #if defined(HAVE_PRI_CCSS)
08387 /*!
08388  * \brief Begin monitoring a busy device.
08389  * \since 1.8
08390  *
08391  * \param agent CC core agent control.
08392  *
08393  * \details
08394  * The core will call this callback if the callee becomes
08395  * available but the caller has reported that he is busy.
08396  * The agent should begin monitoring the caller's device.
08397  * When the caller becomes available again, the agent should
08398  * call ast_cc_agent_caller_available.
08399  *
08400  * \retval 0 on success.
08401  * \retval -1 on error.
08402  */
08403 int sig_pri_cc_agent_start_monitoring(struct ast_cc_agent *agent)
08404 {
08405    /* libpri already knows when and how it needs to monitor Party A. */
08406    return 0;
08407 }
08408 #endif   /* defined(HAVE_PRI_CCSS) */
08409 
08410 #if defined(HAVE_PRI_CCSS)
08411 /*!
08412  * \brief Alert the caller that it is time to try recalling.
08413  * \since 1.8
08414  *
08415  * \param agent CC core agent control.
08416  *
08417  * \details
08418  * The core will call this function when it receives notice
08419  * that a monitored party has become available.
08420  *
08421  * The agent's job is to send a message to the caller to
08422  * notify it of such a change. If the agent is able to
08423  * discern that the caller is currently unavailable, then
08424  * the agent should react by calling the ast_cc_caller_unavailable
08425  * function.
08426  *
08427  * \retval 0 on success.
08428  * \retval -1 on error.
08429  */
08430 int sig_pri_cc_agent_callee_available(struct ast_cc_agent *agent)
08431 {
08432    struct sig_pri_cc_agent_prv *cc_pvt;
08433 
08434    cc_pvt = agent->private_data;
08435    ast_mutex_lock(&cc_pvt->pri->lock);
08436    pri_cc_remote_user_free(cc_pvt->pri->pri, cc_pvt->cc_id);
08437    ast_mutex_unlock(&cc_pvt->pri->lock);
08438    return 0;
08439 }
08440 #endif   /* defined(HAVE_PRI_CCSS) */
08441 
08442 #if defined(HAVE_PRI_CCSS)
08443 /*!
08444  * \brief Destroy private data on the agent.
08445  * \since 1.8
08446  *
08447  * \param agent CC core agent control.
08448  *
08449  * \details
08450  * The core will call this function upon completion
08451  * or failure of CC.
08452  *
08453  * \note
08454  * The agent private_data pointer may be NULL if the agent
08455  * constructor failed.
08456  *
08457  * \return Nothing
08458  */
08459 void sig_pri_cc_agent_destructor(struct ast_cc_agent *agent)
08460 {
08461    struct sig_pri_cc_agent_prv *cc_pvt;
08462    int res;
08463 
08464    cc_pvt = agent->private_data;
08465    if (!cc_pvt) {
08466       /* The agent constructor probably failed. */
08467       return;
08468    }
08469    ast_mutex_lock(&cc_pvt->pri->lock);
08470    res = -1;
08471    if (cc_pvt->cc_request_response_pending) {
08472       res = pri_cc_req_rsp(cc_pvt->pri->pri, cc_pvt->cc_id, 2/* short_term_denial */);
08473    }
08474    if (res) {
08475       pri_cc_cancel(cc_pvt->pri->pri, cc_pvt->cc_id);
08476    }
08477    ast_mutex_unlock(&cc_pvt->pri->lock);
08478    ast_free(cc_pvt);
08479 }
08480 #endif   /* defined(HAVE_PRI_CCSS) */
08481 
08482 #if defined(HAVE_PRI_CCSS)
08483 /*!
08484  * \internal
08485  * \brief Return the hash value of the given CC monitor instance object.
08486  * \since 1.8
08487  *
08488  * \param obj pointer to the (user-defined part) of an object.
08489  * \param flags flags from ao2_callback().  Ignored at the moment.
08490  *
08491  * \retval core_id
08492  */
08493 static int sig_pri_cc_monitor_instance_hash_fn(const void *obj, const int flags)
08494 {
08495    const struct sig_pri_cc_monitor_instance *monitor_instance = obj;
08496 
08497    return monitor_instance->core_id;
08498 }
08499 #endif   /* defined(HAVE_PRI_CCSS) */
08500 
08501 #if defined(HAVE_PRI_CCSS)
08502 /*!
08503  * \internal
08504  * \brief Compere the monitor instance core_id key value.
08505  * \since 1.8
08506  *
08507  * \param obj pointer to the (user-defined part) of an object.
08508  * \param arg callback argument from ao2_callback()
08509  * \param flags flags from ao2_callback()
08510  *
08511  * \return values are a combination of enum _cb_results.
08512  */
08513 static int sig_pri_cc_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
08514 {
08515    struct sig_pri_cc_monitor_instance *monitor_1 = obj;
08516    struct sig_pri_cc_monitor_instance *monitor_2 = arg;
08517 
08518    return monitor_1->core_id == monitor_2->core_id ? CMP_MATCH | CMP_STOP : 0;
08519 }
08520 #endif   /* defined(HAVE_PRI_CCSS) */
08521 
08522 #if defined(HAVE_PRI_CCSS)
08523 /*!
08524  * \brief Request CCSS.
08525  * \since 1.8
08526  *
08527  * \param monitor CC core monitor control.
08528  * \param available_timer_id Where to put the available timer scheduler id.
08529  * Will never be NULL for a device monitor.
08530  *
08531  * \details
08532  * Perform whatever steps are necessary in order to request CC.
08533  * In addition, the monitor implementation is responsible for
08534  * starting the available timer in this callback. The scheduler
08535  * ID for the callback must be stored in the parent_link's child_avail_id
08536  * field.
08537  *
08538  * \retval 0 on success
08539  * \retval -1 on failure.
08540  */
08541 int sig_pri_cc_monitor_req_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
08542 {
08543    struct sig_pri_cc_monitor_instance *instance;
08544    int cc_mode;
08545    int res;
08546 
08547    switch (monitor->service_offered) {
08548    case AST_CC_CCBS:
08549       cc_mode = 0;/* CCBS */
08550       break;
08551    case AST_CC_CCNR:
08552       cc_mode = 1;/* CCNR */
08553       break;
08554    default:
08555       /* CC service not supported by ISDN. */
08556       return -1;
08557    }
08558 
08559    instance = monitor->private_data;
08560 
08561    /* libpri handles it's own available timer. */
08562    ast_mutex_lock(&instance->pri->lock);
08563    res = pri_cc_req(instance->pri->pri, instance->cc_id, cc_mode);
08564    ast_mutex_unlock(&instance->pri->lock);
08565 
08566    return res;
08567 }
08568 #endif   /* defined(HAVE_PRI_CCSS) */
08569 
08570 #if defined(HAVE_PRI_CCSS)
08571 /*!
08572  * \brief Suspend monitoring.
08573  * \since 1.8
08574  *
08575  * \param monitor CC core monitor control.
08576  *
08577  * \details
08578  * Implementers must perform the necessary steps to suspend
08579  * monitoring.
08580  *
08581  * \retval 0 on success
08582  * \retval -1 on failure.
08583  */
08584 int sig_pri_cc_monitor_suspend(struct ast_cc_monitor *monitor)
08585 {
08586    struct sig_pri_cc_monitor_instance *instance;
08587 
08588    instance = monitor->private_data;
08589    ast_mutex_lock(&instance->pri->lock);
08590    pri_cc_status(instance->pri->pri, instance->cc_id, 1/* busy */);
08591    ast_mutex_unlock(&instance->pri->lock);
08592 
08593    return 0;
08594 }
08595 #endif   /* defined(HAVE_PRI_CCSS) */
08596 
08597 #if defined(HAVE_PRI_CCSS)
08598 /*!
08599  * \brief Unsuspend monitoring.
08600  * \since 1.8
08601  *
08602  * \param monitor CC core monitor control.
08603  *
08604  * \details
08605  * Perform the necessary steps to unsuspend monitoring.
08606  *
08607  * \retval 0 on success
08608  * \retval -1 on failure.
08609  */
08610 int sig_pri_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
08611 {
08612    struct sig_pri_cc_monitor_instance *instance;
08613 
08614    instance = monitor->private_data;
08615    ast_mutex_lock(&instance->pri->lock);
08616    pri_cc_status(instance->pri->pri, instance->cc_id, 0/* free */);
08617    ast_mutex_unlock(&instance->pri->lock);
08618 
08619    return 0;
08620 }
08621 #endif   /* defined(HAVE_PRI_CCSS) */
08622 
08623 #if defined(HAVE_PRI_CCSS)
08624 /*!
08625  * \brief Status response to an ast_cc_monitor_status_request().
08626  * \since 1.8
08627  *
08628  * \param monitor CC core monitor control.
08629  * \param devstate Current status of a Party A device.
08630  *
08631  * \details
08632  * Alert a monitor as to the status of the agent for which
08633  * the monitor had previously requested a status request.
08634  *
08635  * \note Zero or more responses may come as a result.
08636  *
08637  * \retval 0 on success
08638  * \retval -1 on failure.
08639  */
08640 int sig_pri_cc_monitor_status_rsp(struct ast_cc_monitor *monitor, enum ast_device_state devstate)
08641 {
08642    struct sig_pri_cc_monitor_instance *instance;
08643    int cc_status;
08644 
08645    switch (devstate) {
08646    case AST_DEVICE_UNKNOWN:
08647    case AST_DEVICE_NOT_INUSE:
08648       cc_status = 0;/* free */
08649       break;
08650    case AST_DEVICE_BUSY:
08651    case AST_DEVICE_INUSE:
08652       cc_status = 1;/* busy */
08653       break;
08654    default:
08655       /* Don't know how to interpret this device state into free/busy status. */
08656       return 0;
08657    }
08658    instance = monitor->private_data;
08659    ast_mutex_lock(&instance->pri->lock);
08660    pri_cc_status_req_rsp(instance->pri->pri, instance->cc_id, cc_status);
08661    ast_mutex_unlock(&instance->pri->lock);
08662 
08663    return 0;
08664 }
08665 #endif   /* defined(HAVE_PRI_CCSS) */
08666 
08667 #if defined(HAVE_PRI_CCSS)
08668 /*!
08669  * \brief Cancel the running available timer.
08670  * \since 1.8
08671  *
08672  * \param monitor CC core monitor control.
08673  * \param sched_id Available timer scheduler id to cancel.
08674  * Will never be NULL for a device monitor.
08675  *
08676  * \details
08677  * In most cases, this function will likely consist of just a
08678  * call to AST_SCHED_DEL. It might have been possible to do this
08679  * within the core, but unfortunately the mixture of sched_thread
08680  * and sched usage in Asterisk prevents such usage.
08681  *
08682  * \retval 0 on success
08683  * \retval -1 on failure.
08684  */
08685 int sig_pri_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
08686 {
08687    /*
08688     * libpri maintains it's own available timer as one of:
08689     * T_CCBS2/T_CCBS5/T_CCBS6/QSIG_CCBS_T2
08690     * T_CCNR2/T_CCNR5/T_CCNR6/QSIG_CCNR_T2
08691     */
08692    return 0;
08693 }
08694 #endif   /* defined(HAVE_PRI_CCSS) */
08695 
08696 #if defined(HAVE_PRI_CCSS)
08697 /*!
08698  * \brief Destroy PRI private data on the monitor.
08699  * \since 1.8
08700  *
08701  * \param monitor_pvt CC device monitor private data pointer.
08702  *
08703  * \details
08704  * Implementers of this callback are responsible for destroying
08705  * all heap-allocated data in the monitor's private_data pointer, including
08706  * the private_data itself.
08707  */
08708 void sig_pri_cc_monitor_destructor(void *monitor_pvt)
08709 {
08710    struct sig_pri_cc_monitor_instance *instance;
08711 
08712    instance = monitor_pvt;
08713    if (!instance) {
08714       return;
08715    }
08716    ao2_unlink(sig_pri_cc_monitors, instance);
08717    ao2_ref(instance, -1);
08718 }
08719 #endif   /* defined(HAVE_PRI_CCSS) */
08720 
08721 /*!
08722  * \brief Load the sig_pri submodule.
08723  * \since 1.8
08724  *
08725  * \param cc_type_name CC type name to use when looking up agent/monitor.
08726  *
08727  * \retval 0 on success.
08728  * \retval -1 on error.
08729  */
08730 int sig_pri_load(const char *cc_type_name)
08731 {
08732 #if defined(HAVE_PRI_CCSS)
08733    sig_pri_cc_type_name = cc_type_name;
08734    sig_pri_cc_monitors = ao2_container_alloc(37, sig_pri_cc_monitor_instance_hash_fn,
08735       sig_pri_cc_monitor_instance_cmp_fn);
08736    if (!sig_pri_cc_monitors) {
08737       return -1;
08738    }
08739 #endif   /* defined(HAVE_PRI_CCSS) */
08740    return 0;
08741 }
08742 
08743 /*!
08744  * \brief Unload the sig_pri submodule.
08745  * \since 1.8
08746  *
08747  * \return Nothing
08748  */
08749 void sig_pri_unload(void)
08750 {
08751 #if defined(HAVE_PRI_CCSS)
08752    if (sig_pri_cc_monitors) {
08753       ao2_ref(sig_pri_cc_monitors, -1);
08754       sig_pri_cc_monitors = NULL;
08755    }
08756 #endif   /* defined(HAVE_PRI_CCSS) */
08757 }
08758 
08759 #endif /* HAVE_PRI */

Generated on 7 Sep 2017 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1