Fri Jan 18 19:56:46 2013

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

Generated on 18 Jan 2013 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1