Sat Apr 26 2014 22:01:42

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