Mon Apr 28 2014 10:05:47

Asterisk developer's documentation


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