Sat Jul 12 2014 17:18:38

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